Spring Security Token Authentication 如何进行身份验证?

Posted

技术标签:

【中文标题】Spring Security Token Authentication 如何进行身份验证?【英文标题】:Spring Security Token Authentication How to Authenticate? 【发布时间】:2016-02-10 14:41:04 【问题描述】:

我正在构建一个基于 Spring、Jersey、Spring Security 和 Tomcat 的 RESTful API。我发现这个教程看起来很棒,但它从来没有讨论如何真正验证用户,这似乎是一个主要部分 (Stateless Authentication with Spring Security and JWT)

无论如何,我的实现都是以此为基础的,现在我正在努力弄清楚如何进行身份验证并取回令牌。

我在下面提供了我认为的所有相关代码。现在的问题是我如何真正进行身份验证并取回令牌?

我尝试了这个,但我没有在响应标头中返回 Token。

@Component
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
public class AuthenticationEndPoint 

    private UserSecurityService userService;

    @Inject
    public AuthenticationEndPoint(UserSecurityService userService) 
        this.userService = userService;
    

    @POST
    public void doSomething(CredentialsDTO credentials) 
        SecurityUser user = userService.loadUserByUsername(credentials.getUserName());
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),credentials.getPassword(),user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);
    

这是我的 Spring Security 配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter 

    @Inject
    private StatelessAuthenticationFilter statelessAuthenticationFilter;

    @Inject
    private UserSecurityService userSecurityService;

    @Inject
    public SecurityConfig() 
        super(true);
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .exceptionHandling().and()
                .anonymous().and()
                .servletApi().and()
                .headers().cacheControl().and()
                .authorizeRequests()

                // allow anonymous resource requests
                .antMatchers("/").permitAll()
                .antMatchers("/favicon.ico").permitAll()
                .antMatchers("/public/**").permitAll()

                // allow login
                .antMatchers("/api/auth").permitAll()

                // all other requests require authentication
                .anyRequest().authenticated().and()

                // token based authentication
                .addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(userSecurityService).passwordEncoder(bCryptPasswordEncoder());
    

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() 
        return new BCryptPasswordEncoder();
    

    @Bean
    public AuthenticationManager authenticationManager() throws Exception 
        return super.authenticationManagerBean();
    

自定义用户:

public class SecurityUser extends User 

    private org.company.app.domain.User user;

    public SecurityUser(org.company.app.domain.User user,
                        Collection<GrantedAuthority> grantedAuthorities) 
        super(user.getEmail(),user.getPasswordEncoded(),grantedAuthorities);
        this.user = user;
    

    public org.company.app.domain.User getUser() 
        return user;
    

    public void setUser(org.company.app.domain.User user) 
        this.user = user;
    

    public Collection<Role> getRoles() 
        return this.user.getRoles();
    

    @Override
    public String toString() 
        return MoreObjects.toStringHelper(this)
                .add("user", user)
                .toString();
    

过滤器:

@Service
public class StatelessAuthenticationFilter extends GenericFilterBean 

    private final TokenAuthenticationService tokenAuthenticationService;

    @Inject
    public StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) 
        this.tokenAuthenticationService = tokenAuthenticationService;
    

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException 
        Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) servletRequest);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(servletRequest, servletResponse);
        SecurityContextHolder.getContext().setAuthentication(null);
    

令牌认证服务

@Service
public class TokenAuthenticationService 

    private static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";

    private final TokenHandler tokenHandler;

    @Inject
    public TokenAuthenticationService(TokenHandler tokenHandler) 
        this.tokenHandler = tokenHandler;
    

    public String addAuthentication(HttpServletResponse response, UserAuthentication authentication) 
        final SecurityUser user = (SecurityUser) authentication.getDetails();
        String token = tokenHandler.createTokenForUser(user);
        response.addHeader(AUTH_HEADER_NAME, token);
        return token;
    

    public Authentication getAuthentication(HttpServletRequest request) 
        final String token = request.getHeader(AUTH_HEADER_NAME);
        if (token != null) 
            final SecurityUser user = tokenHandler.parseUserFromToken(token);
            if (user != null) 
                return new UserAuthentication(user);
            
        
        return null;
    

令牌处理程序:

@Service
public class TokenHandler 

    private Environment environment;
    private final UserSecurityService userService;
    private final String secret;

    @Inject
    public TokenHandler(Environment environment, UserSecurityService userService) 
        this.environment = environment;
        this.secret = this.environment.getRequiredProperty("application.security.secret");
        this.userService = userService;
    

    public SecurityUser parseUserFromToken(String token) 
        String username = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        return userService.loadUserByUsername(username);
    

    public String createTokenForUser(SecurityUser user) 
        return Jwts.builder()
                .setSubject(user.getUsername())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    

Spring Security Authentication接口的实现

public class UserAuthentication implements Authentication 

    private final SecurityUser user;
    private boolean authenticated = true;

    public UserAuthentication(SecurityUser user) 
        this.user = user;
    

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() 
        return user.getAuthorities();
    

    @Override
    public Object getCredentials() 
        return user.getPassword();
    

    @Override
    public Object getDetails() 
        return user;
    

    @Override
    public Object getPrincipal() 
        return user.getUsername();
    

    @Override
    public boolean isAuthenticated() 
        return authenticated;
    

    @Override
    public void setAuthenticated(boolean b) throws IllegalArgumentException 
        this.authenticated = b;
    

    @Override
    public String getName() 
        return user.getUsername();
    

终于实现了我的 UserDetailsS​​ervice 接口

@Service
public class UserSecurityService implements UserDetailsService 

    private static final Logger logger = LoggerFactory.getLogger(UserSecurityService.class);

    private UserService userService;

    @Inject
    public UserSecurityService(UserService userService) 
        this.userService = userService;
    

    private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();

    @Override
    public SecurityUser loadUserByUsername(String s) throws UsernameNotFoundException 

        logger.debug("Attempting authentication with identifier ", s);

        User user = userService.getUserByUserName(s);
        if (user == null) 
            throw new UsernameNotFoundException(String.format("User with identifier %s was not found",s));
        

        Collection<GrantedAuthority> authorities = new HashSet<>();
        for (Role role : user.getRoles()) 
            authorities.add(new SimpleGrantedAuthority(role.getSpringName()));
        

        return new SecurityUser(user,authorities);
    

【问题讨论】:

这个问题你解决了吗?? 【参考方案1】:

我们在我们的项目中做了类似的事情。我们将 JWT 令牌作为响应正文的一部分发送。 用 AngularJS 编写的客户端获取令牌并存储在浏览器内存中。 然后对于所有后续的安全调用,客户端将令牌作为承载令牌嵌入到请求标头中。 我们用于身份验证的 JSON 如下所示:


    "username": "auser",
    "password": "password",
    "dbname": "data01"  

对于每个常见的请求,我们在请求标头中添加以下内容

Bearer <token>

【讨论】:

以上是关于Spring Security Token Authentication 如何进行身份验证?的主要内容,如果未能解决你的问题,请参考以下文章

后端架构token授权认证机制:spring security JSON Web Token(JWT)简例

后端架构token授权认证机制:spring security JSON Web Token(JWT)简例

Spring Security框架下Restful Token的验证方案

Spring Security 结合了 Container Security 和 JWT Token

redis jwt spring boot spring security 实现api token 验证

spring security 的jwt认证以及原理解析