Search in sources :

Example 1 with DefaultRedirectStrategy

use of org.springframework.security.web.DefaultRedirectStrategy in project app-template by xtuer.

the class OAuthAuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    // 被拦截到说明是 QQ 登陆成功的回调地址 http://host:port/oauth/qq/callback
    if (request.getRequestURI().startsWith("/oauth/qq/callback")) {
        // [1] 获取 code
        String code = request.getParameter("code");
        System.out.println("Code: " + code);
        // [2] 用 code 换取 access token
        // 响应: access_token=1A2CF189A4BBEE25CACE587CDD106512&expires_in=7776000&refresh_token=A5A3B6D90955ED6934EC42F2EECDA4BC
        String accessTokenUrl = String.format(QQ_ACCESS_TOKEN_URL, qqClientId, qqClientSecret, QQ_CALLBACK, code);
        String responseData = HttpClient.get(accessTokenUrl).execute().asString();
        String token = responseData.replaceAll("access_token=(.+)&expires_in=.+", "$1");
        System.out.println("Access Token: " + token);
        // [3] 用 access token 获取用户的 open ID
        // 响应: callback( {"client_id":"101292272","openid":"4584E3AAABFC5F052971C278790E9FCF"} );
        String openIdUrl = String.format(QQ_OPEN_ID_URL, token);
        responseData = HttpClient.get(openIdUrl).execute().asString();
        int start = responseData.indexOf("{");
        int end = responseData.lastIndexOf("}") + 1;
        String json = responseData.substring(start, end);
        String openId = JSON.parseObject(json).getString("openid");
        System.out.println("Open ID: " + openId);
        // [4] 使用 openId 查找用户
        // 假设 admin 是使用 open id 查找到的用户吧
        User user = new User("admin", "----", "ROLE_ADMIN");
        if (user != null) {
            // [5] 用户存在,登陆成功,跳转到登陆前的页面
            Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
            // 跳转到登陆前页面
            super.successfulAuthentication(request, response, chain, auth);
        } else {
            // [6] 用户不存在,跳转到 "创建|绑定已有用户" 页面,
            // 绑定好用户后保存用户信息到: SecurityContextHolder.getContext().setAuthentication(auth)
            // 然后跳转到登陆前的页面
            DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, "/page/bindUser");
        }
        return;
    } else if (request.getRequestURI().startsWith("/oauth/weixin/callback")) {
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) User(ebag.bean.User) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) DefaultRedirectStrategy(org.springframework.security.web.DefaultRedirectStrategy) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 2 with DefaultRedirectStrategy

use of org.springframework.security.web.DefaultRedirectStrategy in project coffeenet-starter by coffeenet.

the class IntegrationCoffeeNetSecurityConfigurationTest method configureCorrectDefaultLoginFailureUrl.

@Test
public void configureCorrectDefaultLoginFailureUrl() throws IOException, ServletException {
    CoffeeNetSecurityProperties coffeeNetSecurityProperties = new CoffeeNetSecurityProperties();
    coffeeNetSecurityProperties.setDefaultLoginFailureUrl("/this-is-a-test-url");
    IntegrationCoffeeNetSecurityConfiguration sut = new IntegrationCoffeeNetSecurityConfiguration(new CoffeeNetSecurityClientProperties(), new CoffeeNetSecurityResourceProperties(), coffeeNetSecurityProperties);
    CoffeeNetSimpleUrlAuthenticationFailureHandler authenticationFailureHandler = (CoffeeNetSimpleUrlAuthenticationFailureHandler) sut.defaultAuthenticationFailureHandler();
    DefaultRedirectStrategy redirectStrategyMock = mock(DefaultRedirectStrategy.class);
    authenticationFailureHandler.setRedirectStrategy(redirectStrategyMock);
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    AuthenticationServiceException test = new AuthenticationServiceException("test");
    authenticationFailureHandler.onAuthenticationFailure(request, response, test);
    verify(redirectStrategyMock).sendRedirect(request, response, "/this-is-a-test-url");
}
Also used : IntegrationCoffeeNetSecurityConfiguration(rocks.coffeenet.autoconfigure.security.config.CoffeeNetSecurityAutoConfiguration.IntegrationCoffeeNetSecurityConfiguration) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DefaultRedirectStrategy(org.springframework.security.web.DefaultRedirectStrategy) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) Test(org.junit.Test)

Example 3 with DefaultRedirectStrategy

use of org.springframework.security.web.DefaultRedirectStrategy in project judge by zjnu-acm.

the class SecurityConfiguration method configure.

@Override
protected void configure(HttpSecurity http) throws Exception {
    SimpleUrlAuthenticationSuccessHandler simpleUrlAuthenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler("/");
    simpleUrlAuthenticationSuccessHandler.setUseReferer(false);
    simpleUrlAuthenticationSuccessHandler.setTargetUrlParameter("url");
    DefaultRedirectStrategy defaultRedirectStrategy = new DefaultRedirectStrategy();
    simpleUrlAuthenticationSuccessHandler.setRedirectStrategy(defaultRedirectStrategy);
    SimpleUrlLogoutSuccessHandler simpleUrlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
    simpleUrlLogoutSuccessHandler.setUseReferer(true);
    // @formatter:off
    http.authorizeRequests().antMatchers(ckfinder.getServlet().getPath()).hasAnyRole("ADMIN").and().csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().formLogin().loginPage("/login").usernameParameter("user_id1").passwordParameter("password1").successHandler(simpleUrlAuthenticationSuccessHandler).failureHandler(failureHandler()).permitAll().and().headers().cacheControl().disable().httpStrictTransportSecurity().disable().frameOptions().sameOrigin().and().logout().logoutUrl("/logout.html").logoutSuccessHandler(simpleUrlLogoutSuccessHandler).permitAll().and().rememberMe().rememberMeParameter("rememberMe").tokenRepository(persistentTokenRepository).and().requestCache().requestCache(new NullRequestCache()).and().servletApi();
// @formatter:on
}
Also used : SimpleUrlAuthenticationSuccessHandler(org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler) DefaultRedirectStrategy(org.springframework.security.web.DefaultRedirectStrategy) SimpleUrlLogoutSuccessHandler(org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler) NullRequestCache(org.springframework.security.web.savedrequest.NullRequestCache)

Example 4 with DefaultRedirectStrategy

use of org.springframework.security.web.DefaultRedirectStrategy in project spring-security by spring-projects.

the class SwitchUserFilterTests method redirectOmitsContextPathIfUseRelativeContextSet.

@Test
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
    // set current user
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
    SecurityContextHolder.getContext().setAuthentication(auth);
    MockHttpServletRequest request = createMockSwitchRequest();
    request.setContextPath("/webapp");
    request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
    request.setRequestURI("/webapp/login/impersonate");
    SwitchUserFilter filter = new SwitchUserFilter();
    filter.setSwitchUserUrl("/login/impersonate");
    SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl");
    DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy();
    contextRelativeRedirector.setContextRelative(true);
    switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
    filter.setSuccessHandler(switchSuccessHandler);
    filter.setUserDetailsService(new MockUserDetailsService());
    FilterChain chain = mock(FilterChain.class);
    MockHttpServletResponse response = new MockHttpServletResponse();
    filter.doFilter(request, response, chain);
    verify(chain, never()).doFilter(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) SimpleUrlAuthenticationSuccessHandler(org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler) DefaultRedirectStrategy(org.springframework.security.web.DefaultRedirectStrategy) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

DefaultRedirectStrategy (org.springframework.security.web.DefaultRedirectStrategy)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 SimpleUrlAuthenticationSuccessHandler (org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler)2 User (ebag.bean.User)1 FilterChain (jakarta.servlet.FilterChain)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Test (org.junit.Test)1 Test (org.junit.jupiter.api.Test)1 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)1 Authentication (org.springframework.security.core.Authentication)1 SimpleUrlLogoutSuccessHandler (org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler)1 NullRequestCache (org.springframework.security.web.savedrequest.NullRequestCache)1 IntegrationCoffeeNetSecurityConfiguration (rocks.coffeenet.autoconfigure.security.config.CoffeeNetSecurityAutoConfiguration.IntegrationCoffeeNetSecurityConfiguration)1