springboot集成JWT实现登陆验证

x33g5p2x  于2022-05-28 转载在 Spring  
字(3.6k)|赞(0)|评价(0)|浏览(456)

1:首先,我们需要在项目中导入两个依赖:

  1. <dependency>
  2. <groupId>com.auth0</groupId>
  3. <artifactId>java-jwt</artifactId>
  4. <version>3.10.3</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.hutool</groupId>
  8. <artifactId>hutool-all</artifactId>
  9. <version>5.7.20</version>
  10. </dependency>

2:然后我讲一下需求:前端给后端传入一个form-data类型数据,然后数据库中现在已经有了一条管理员用户(看下面第二个图)

(1):我们的思路就是首先获取到前端传来的值,然后使用前端传来的用户名去数据库中查,我们前端传来的数据我是用了一个封装实体类:UserDto来保存前端传来的值:

(2):然后我们将根据用户名查出来的数据会返回出一个实体类,我们使用get方法得到他的salt:(也就是数据库中的salt)

(3):接下来,我们将前端传来的密码和数据库中查到的salt加起来,组成新的字符串,然后将新的字符串进行SHA-256加密,将加密处理后的密码去和数据库中的密码比对是否相等,这里上面那个图片也圈住了,至于这句话: String s1 = HexUtils.toHexString(MessageDigest.getInstance("SHA-256").digest(s.getBytes()));就是使用SHA-256加密

如果相等就返回给前端数据:下图是前端需要响应的代码示例,所以我们将中间的data返回数据使用HashMap封装起来,至于外面的code和msg就是使用一个封装类:

3:涉及到的一些工具类和跨域:

TokenUtils:创建token中的sign,我们传入的第一个就是数据库中实体类,这里一定不要混淆,数据库中数据的实体类和前端传来参数的封装实体类,我这里数据库中的实体类是:AdminLogin:,然后第二个参数expires是指过期时间,这个我们自己设置就好,需要自己修改的地方还有就是:

  1. .withClaim("username",user.getLoginName()) //存放数据
  2. .withClaim("password",user.getPassword())

这里的user.getxxxxxx根据自己去调整

  1. package com.example.check.util;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.JWTVerifier;
  4. import com.auth0.jwt.algorithms.Algorithm;
  5. import com.auth0.jwt.exceptions.JWTCreationException;
  6. import com.auth0.jwt.exceptions.JWTDecodeException;
  7. import com.auth0.jwt.exceptions.JWTVerificationException;
  8. import com.auth0.jwt.interfaces.Claim;
  9. import com.auth0.jwt.interfaces.DecodedJWT;
  10. import com.example.check.entity.AdminLogin;
  11. import java.util.Date;
  12. /**
  13. * @author quxiang
  14. * @date 2021/12/30 13:53
  15. */
  16. public class TokenUtil {
  17. private static final long EXPIRE_TIME= 60*1000;//token到期时间60s
  18. private static final String TOKEN_SECRET="l122adasw532df"; //密钥盐
  19. /**
  20. * 创建一个token
  21. * @param user
  22. * @return
  23. */
  24. public static String sign(AdminLogin user,Date expires){
  25. String token=null;
  26. try {
  27. token = JWT.create()
  28. .withIssuer("auth0")//发行人
  29. .withClaim("username",user.getLoginName()) //存放数据
  30. .withClaim("password",user.getPassword())
  31. .withExpiresAt(expires)//过期时间
  32. .sign(Algorithm.HMAC256(TOKEN_SECRET));
  33. } catch (IllegalArgumentException|JWTCreationException je) {
  34. }
  35. return token;
  36. }
  37. /**
  38. * 对token进行验证
  39. * @param token
  40. * @return
  41. */
  42. public static Boolean verify(String token){
  43. try {
  44. JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
  45. DecodedJWT decodedJWT=jwtVerifier.verify(token);
  46. System.out.println("认证通过:");
  47. System.out.println("username: " + TokenUtil.getUsername(token));
  48. System.out.println("过期时间: " + decodedJWT.getExpiresAt());
  49. } catch (IllegalArgumentException |JWTVerificationException e) {
  50. //抛出错误即为验证不通过
  51. return false;
  52. }
  53. return true;
  54. }
  55. /**
  56. * 获取用户名
  57. */
  58. public static String getUsername(String token)
  59. {
  60. try{
  61. DecodedJWT jwt=JWT.decode(token);
  62. return jwt.getClaim("username").asString();
  63. }catch (JWTDecodeException e)
  64. {
  65. return null;
  66. }
  67. }
  68. }

跨域:

  1. package com.example.check.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  5. /**
  6. * 跨域配置
  7. */
  8. @Configuration
  9. public class WebMvcConfig implements WebMvcConfigurer {
  10. @Override
  11. public void addCorsMappings(CorsRegistry registry) {
  12. registry.addMapping("/**")
  13. .allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
  14. .allowedMethods("*")
  15. .allowedOriginPatterns("*")
  16. .allowCredentials(true);
  17. }
  18. }

然后我们打开前端界面:点击登录后就可以在后台看到已经传过去的参数:

结束!

相关文章

目录