Java Spring Security. Logged user information

ChadDeveloPLer :

I want to improve my REST API todo application. I want to add to security configuration, when someone logs in I want to redirect him to endpoint with his generated by Utils userId. I want to achive something like that:

            .formLogin().defaultSuccessUrl("/users/(logged in our session userId)").permitAll()
k.hammouch :

you can do it by adding this few things :

in your configure method in WebSecurityConfigurerAdapter add this line :

.formLogin().successHandler(mySuccessHandler())...

add a bean definition by adding

@Bean
public AuthenticationSuccessHandler mySuccessHandler(){
    return new MyCustomAuthenticationSuccessHandler();
}

next you need to create the MyCustomAuthenticationSuccessHandler that implements AuthenticationSuccessHandler.

public class MyCustomAuthenticationSuccessHandler
  implements AuthenticationSuccessHandler {

    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {

        handle(request, response, authentication);
    }

    protected void handle(
        HttpServletRequest request,
        HttpServletResponse response, 
        Authentication authentication
    ) throws IOException {

        String targetUrl = determineYourTargetUrl(request);

        if (response.isCommitted()) {
            logger.debug(
                "Response has already been committed. Unable to redirect to "
                        + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineYourTargetUrl(HttpServletRequest request) {
        return "users/" + request.getSession().getId();
    }


}

Hope that will help you.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379426&siteId=1