如何使用Spring Boot Security设置手动认证用户

时间:2018-11-09 09:49:25

标签: spring spring-boot spring-security

我用SSO登录创建了Spring Boot应用程序。我已经使用saml.xml文件了。登录SSO后,我调用了getAuthentication()方法,它将返回annonymousUser 每次。我想获取SSO登录用户的详细信息。

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

安全配置类如下所示:

@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 个答案:

答案 0 :(得分:0)

您可以像下面那样使用户登录到spring安全。

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);
}

引用manually-set-user-authentication-spring-security