简体   繁体   中英

Spring Security login programmatically (AuthenticationSuccessHandler)

I'm using spring-security 3.2.6 and during testing I programmatically login my users with

public User login(User user) {
    logOut();
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user, user.getPassword(), user.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(
            authenticationToken);
    return user;
}

doing it in that way I notice that isn't going through the AuthenticationSuccessHandler . Is there any way to achieve that?

What you are doing is trying to override the AuthenticationManager. When you want to override AuthentitionSeccessHandler then you need to

Override the AuthenticationFilter.

Authentication filter checks if the incoming request needs authentication, if Yes then calls the Authentication Manager to authenticate the request . Authentication Manager authenticates request and add it to SecurityContextHolder and returns the Authrntication token which is dy default UsernamePasswordAuthenticationToken.

Filter then checks if there is a SuccessHandler defined. If yes then redirects the request to the AuthenticationSuccessHandler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM