How to set Manually Authenticate User with Spring boot Security

Viewed 5084

I Created Spring boot application with SSO login. I have used saml.xml file for it. After SSO login i called getAuthentication() method it will return annonymousUser every time. I want to get SSO Logged User details.

Principal principal = 
        SecurityContextHolder.getContext().getAuthentication();

Security configuration class look like following :

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/actuator").authenticated();
    http.headers().cacheControl().disable();
    http.csrf().disable();
    http.logout().logoutSuccessUrl("/assets/logout.html");
}
}
1 Answers

You can make user login into spring security like below.

public void login(HttpServletRequest req, String user, String pass) { 
    UsernamePasswordAuthenticationToken authReq
      = new UsernamePasswordAuthenticationToken(user, pass);
    Authentication auth = authManager.authenticate(authReq);

    SecurityContext sc = SecurityContextHolder.getContext();
    sc.setAuthentication(auth);
    HttpSession session = req.getSession(true);
    session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}

Refer manually-set-user-authentication-spring-security

Related