我正在基于Spring,Jersey,Spring Security和Tomcat构建RESTful API。我发现本教程看起来很棒,但是它从未讨论过如何实际验证用户身份,这似乎很重要(Stateless Authentication with Spring Security and JWT

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

我提供了以下所有相关代码。现在的问题是,我如何真正进行身份验证并获得令牌?

我尝试了一下,但没有在响应头中重新获得令牌。

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

最佳答案

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

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


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

Bearer <token>

07-24 09:21