服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Springboot集成Spring Security实现JWT认证的步骤详解

Springboot集成Spring Security实现JWT认证的步骤详解

2021-08-05 11:06南瓜慢说 Java教程

这篇文章主要介绍了Springboot集成Spring Security实现JWT认证的步骤详解,帮助大家更好的理解和使用springboot,感兴趣的朋友可以了解下

1 简介

Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐。而作为前后端分离的SSO方案,JWT也在许多项目中应用。本文将介绍如何通过Spring Security实现JWT认证。

用户与服务器交互大概如下:

Springboot集成Spring Security实现JWT认证的步骤详解

  1. 客户端获取JWT,一般通过POST方法把用户名/密码传给server;
  2. 服务端接收到客户端的请求后,会检验用户名/密码是否正确,如果正确则生成JWT并返回;不正确则返回错误;
  3. 客户端拿到JWT后,在有效期内都可以通过JWT来访问资源了,一般把JWT放在请求头;一次获取,多次使用;
  4. 服务端校验JWT是否合法,合法则允许客户端正常访问,不合法则返回401。

2 项目整合

我们把要整合的Spring Security和JWT加入到项目的依赖中去:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-security</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>io.jsonwebtoken</groupId>
  11. <artifactId>jjwt</artifactId>
  12. <version>0.9.1</version>
  13. </dependency>

2.1 JWT整合

2.1.1 JWT工具类

JWT工具类起码要具有以下功能:

  • 根据用户信息生成JWT;
  • 校验JWT是否合法,如是否被篡改、是否过期等;
  • 从JWT中解析用户信息,如用户名、权限等;

具体代码如下:

  1. @Component
  2. public class JwtTokenProvider {
  3.  
  4. @Autowired JwtProperties jwtProperties;
  5.  
  6. @Autowired
  7. private CustomUserDetailsService userDetailsService;
  8.  
  9. private String secretKey;
  10.  
  11. @PostConstruct
  12. protected void init() {
  13. secretKey = Base64.getEncoder().encodeToString(jwtProperties.getSecretKey().getBytes());
  14. }
  15.  
  16. public String createToken(String username, List<String> roles) {
  17.  
  18. Claims claims = Jwts.claims().setSubject(username);
  19. claims.put("roles", roles);
  20.  
  21. Date now = new Date();
  22. Date validity = new Date(now.getTime() + jwtProperties.getValidityInMs());
  23.  
  24. return Jwts.builder()//
  25. .setClaims(claims)//
  26. .setIssuedAt(now)//
  27. .setExpiration(validity)//
  28. .signWith(SignatureAlgorithm.HS256, secretKey)//
  29. .compact();
  30. }
  31.  
  32. public Authentication getAuthentication(String token) {
  33. UserDetails userDetails = this.userDetailsService.loadUserByUsername(getUsername(token));
  34. return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
  35. }
  36.  
  37. public String getUsername(String token) {
  38. return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
  39. }
  40.  
  41. public String resolveToken(HttpServletRequest req) {
  42. String bearerToken = req.getHeader("Authorization");
  43. if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
  44. return bearerToken.substring(7);
  45. }
  46. return null;
  47. }
  48.  
  49. public boolean validateToken(String token) {
  50. try {
  51. Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
  52.  
  53. if (claims.getBody().getExpiration().before(new Date())) {
  54. return false;
  55. }
  56.  
  57. return true;
  58. } catch (JwtException | IllegalArgumentException e) {
  59. throw new InvalidJwtAuthenticationException("Expired or invalid JWT token");
  60. }
  61. }
  62.  
  63. }

工具类还实现了另一个功能:从HTTP请求头中获取JWT。

2.1.2 Token处理的Filter

Filter是Security处理的关键,基本上都是通过Filter来拦截请求的。首先从请求头取出JWT,然后校验JWT是否合法,如果合法则取出Authentication保存在SecurityContextHolder里。如果不合法,则做异常处理。

  1. public class JwtTokenAuthenticationFilter extends GenericFilterBean {
  2.  
  3. private JwtTokenProvider jwtTokenProvider;
  4.  
  5. public JwtTokenAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
  6. this.jwtTokenProvider = jwtTokenProvider;
  7. }
  8.  
  9. @Override
  10. public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
  11. throws IOException, ServletException {
  12. HttpServletRequest request = (HttpServletRequest) req;
  13. HttpServletResponse response = (HttpServletResponse) res;
  14.  
  15. try {
  16. String token = jwtTokenProvider.resolveToken(request);
  17. if (token != null && jwtTokenProvider.validateToken(token)) {
  18. Authentication auth = jwtTokenProvider.getAuthentication(token);
  19.  
  20. if (auth != null) {
  21. SecurityContextHolder.getContext().setAuthentication(auth);
  22. }
  23. }
  24. } catch (InvalidJwtAuthenticationException e) {
  25. response.setStatus(HttpStatus.UNAUTHORIZED.value());
  26. response.getWriter().write("Invalid token");
  27. response.getWriter().flush();
  28. return;
  29. }
  30.  
  31. filterChain.doFilter(req, res);
  32. }
  33. }

对于异常处理,使用@ControllerAdvice是不行的,应该这个是Filter,在这里抛的异常还没有到DispatcherServlet,无法处理。所以Filter要自己做异常处理:

  1. catch (InvalidJwtAuthenticationException e) {
  2. response.setStatus(HttpStatus.UNAUTHORIZED.value());
  3. response.getWriter().write("Invalid token");
  4. response.getWriter().flush();
  5. return;
  6. }

最后的return不能省略,因为已经要把输出的内容给Response了,没有必要再往后传递,否则报错

  1. java.lang.IllegalStateException: getWriter() has already been called

2.1.3 JWT属性

JWT需要配置一个密钥来加密,同时还要配置JWT令牌的有效期。

  1. @Configuration
  2. @ConfigurationProperties(prefix = "pkslow.jwt")
  3. public class JwtProperties {
  4. private String secretKey = "pkslow.key";
  5. private long validityInMs = 3600_000;
  6. //getter and setter
  7. }

2.2 Spring Security整合

Spring Security的整个框架还是比较复杂的,简化后大概如下图所示:

Springboot集成Spring Security实现JWT认证的步骤详解

它是通过一连串的Filter来进行安全管理。细节这里先不展开讲。

2.2.1 WebSecurityConfigurerAdapter配置

这个配置也可以理解为是FilterChain的配置,可以不用理解,代码很好懂它做了什么:

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3.  
  4. @Autowired
  5. JwtTokenProvider jwtTokenProvider;
  6.  
  7. @Bean
  8. @Override
  9. public AuthenticationManager authenticationManagerBean() throws Exception {
  10. return super.authenticationManagerBean();
  11. }
  12.  
  13. @Bean
  14. public PasswordEncoder passwordEncoder() {
  15. return NoOpPasswordEncoder.getInstance();
  16. }
  17.  
  18. @Override
  19. protected void configure(HttpSecurity http) throws Exception {
  20. http
  21. .httpBasic().disable()
  22. .csrf().disable()
  23. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  24. .and()
  25. .authorizeRequests()
  26. .antMatchers("/auth/login").permitAll()
  27. .antMatchers(HttpMethod.GET, "/admin").hasRole("ADMIN")
  28. .antMatchers(HttpMethod.GET, "/user").hasRole("USER")
  29. .anyRequest().authenticated()
  30. .and()
  31. .apply(new JwtSecurityConfigurer(jwtTokenProvider));
  32. }
  33. }

这里通过HttpSecurity配置了哪些请求需要什么权限才可以访问。

  • /auth/login用于登陆获取JWT,所以都能访问;
  • /admin只有ADMIN用户才可以访问;
  • /user只有USER用户才可以访问。

而之前实现的Filter则在下面配置使用:

  1. public class JwtSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
  2.  
  3. private JwtTokenProvider jwtTokenProvider;
  4.  
  5. public JwtSecurityConfigurer(JwtTokenProvider jwtTokenProvider) {
  6. this.jwtTokenProvider = jwtTokenProvider;
  7. }
  8.  
  9. @Override
  10. public void configure(HttpSecurity http) throws Exception {
  11. JwtTokenAuthenticationFilter customFilter = new JwtTokenAuthenticationFilter(jwtTokenProvider);
  12. http.exceptionHandling()
  13. .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
  14. .and()
  15. .addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
  16. }
  17. }

2.2.2 用户从哪来

通常在Spring Security的世界里,都是通过实现UserDetailsService来获取UserDetails的。

  1. @Component
  2. public class CustomUserDetailsService implements UserDetailsService {
  3.  
  4. private UserRepository users;
  5.  
  6. public CustomUserDetailsService(UserRepository users) {
  7. this.users = users;
  8. }
  9.  
  10. @Override
  11. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  12. return this.users.findByUsername(username)
  13. .orElseThrow(() -> new UsernameNotFoundException("Username: " + username + " not found"));
  14. }
  15. }

对于UserRepository,可以从数据库中读取,或者其它用户管理中心。为了方便,我使用Map放了两个用户:

  1. @Repository
  2. public class UserRepository {
  3.  
  4. private static final Map<String, User> allUsers = new HashMap<>();
  5.  
  6. @Autowired
  7. private PasswordEncoder passwordEncoder;
  8.  
  9. @PostConstruct
  10. protected void init() {
  11. allUsers.put("pkslow", new User("pkslow", passwordEncoder.encode("123456"), Collections.singletonList("ROLE_ADMIN")));
  12. allUsers.put("user", new User("user", passwordEncoder.encode("123456"), Collections.singletonList("ROLE_USER")));
  13. }
  14.  
  15. public Optional<User> findByUsername(String username) {
  16. return Optional.ofNullable(allUsers.get(username));
  17. }
  18. }

3 测试

完成代码编写后,我们来测试一下:

(1)无JWT访问,失败

  1. curl http://localhost:8080/admin
  2. {"timestamp":"2021-02-06T05:45:06.385+0000","status":403,"error":"Forbidden","message":"Access Denied","path":"/admin"}
  3.  
  4. $ curl http://localhost:8080/user
  5. {"timestamp":"2021-02-06T05:45:16.438+0000","status":403,"error":"Forbidden","message":"Access Denied","path":"/user"}

(2)admin获取JWT,密码错误则失败,密码正确则成功

  1. $ curl http://localhost:8080/auth/login -X POST -d '{"username":"pkslow","password":"xxxxxx"}' -H 'Content-Type: application/json'
  2. {"timestamp":"2021-02-06T05:47:16.254+0000","status":403,"error":"Forbidden","message":"Access Denied","path":"/auth/login"}
  3.  
  4. $ curl http://localhost:8080/auth/login -X POST -d '{"username":"pkslow","password":"123456"}' -H 'Content-Type: application/json'
  5. eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwa3Nsb3ciLCJyb2xlcyI6WyJST0xFX0FETUlOIl0sImlhdCI6MTYxMjU5MDYxNCwiZXhwIjoxNjEyNTkxMjE0fQ.d4Gi50aaOsHHqpM0d8Mh1960otnZf7rlE3x6xSfakVo

(3)admin带JWT访问/admin,成功;访问/user失败

  1. $ curl http://localhost:8080/admin -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwa3Nsb3ciLCJyb2xlcyI6WyJST0xFX0FETUlOIl0sImlhdCI6MTYxMjU5MDYxNCwiZXhwIjoxNjEyNTkxMjE0fQ.d4Gi50aaOsHHqpM0d8Mh1960otnZf7rlE3x6xSfakVo'
  2. you are admin
  3.  
  4. $ curl http://localhost:8080/user -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwa3Nsb3ciLCJyb2xlcyI6WyJST0xFX0FETUlOIl0sImlhdCI6MTYxMjU5MDYxNCwiZXhwIjoxNjEyNTkxMjE0fQ.d4Gi50aaOsHHqpM0d8Mh1960otnZf7rlE3x6xSfakVo'
  5. {"timestamp":"2021-02-06T05:51:23.099+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/user"}

(4)使用过期的JWT访问,失败

  1. $ curl http://localhost:8080/admin -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwa3Nsb3ciLCJyb2xlcyI6WyJST0xFX0FETUlOIl0sImlhdCI6MTYxMjU5MDQ0OSwiZXhwIjoxNjEyNTkwNTA5fQ.CSaubE4iJcYATbLmbb59aNFU1jNCwDFHUV3zIakPU64'
  2. Invalid token

4 总结

代码请查看:https://github.com/LarryDpk/pkslow-samples

以上就是Springboot集成Spring Security实现JWT认证的步骤详解的详细内容,更多关于Springboot集成Spring Security的资料请关注服务器之家其它相关文章!

延伸 · 阅读

精彩推荐