当前位置:   article > 正文

JWT跨域认证

JWT跨域认证

新建shop项目

新建bean包,再其包下新建User

 

  1. package com.example.shop.bean;
  2. public class User {
  3. private String username;
  4. private String password;
  5. // 可以根据需要添加其他字段,比如角色、邮箱等
  6. public String getUsername() {
  7. return username;
  8. }
  9. public void setUsername(String username) {
  10. this.username = username;
  11. }
  12. public String getPassword() {
  13. return password;
  14. }
  15. public void setPassword(String password) {
  16. this.password = password;
  17. }
  18. // 可以根据需要添加其他的 getter 和 setter 方法
  19. @Override
  20. public String toString() {
  21. return "User{" +
  22. "username='" + username + '\'' +
  23. ", password='" + password + '\'' +
  24. '}';
  25. }
  26. }

新建utils包,再其包下新建JwtUtils,Result和ResultCode

 ResultCode代码如下

  1. package com.example.shop.utils;
  2. public interface ResultCode {
  3. public static Integer SUCCESS= 20000;//成功
  4. public static Integer ERROR=20001;//失败
  5. }

Result代码如下

  1. package com.example.shop.utils;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class Result {
  5. private Boolean success;
  6. private Integer code;
  7. private String message;
  8. private Map<String, Object> data = new HashMap<>();
  9. // 私有构造方法
  10. private Result() {}
  11. // 成功静态方法
  12. public static Result ok() {
  13. Result r = new Result();
  14. r.setSuccess(true);
  15. r.setCode(ResultCode.SUCCESS);
  16. r.setMessage("成功");
  17. return r;
  18. }
  19. // 失败静态方法
  20. public static Result error() {
  21. Result r = new Result();
  22. r.setSuccess(false);
  23. r.setCode(ResultCode.ERROR);
  24. r.setMessage("失败");
  25. return r;
  26. }
  27. public Boolean getSuccess() {
  28. return success;
  29. }
  30. public void setSuccess(Boolean success) {
  31. this.success = success;
  32. }
  33. public Integer getCode() {
  34. return code;
  35. }
  36. public void setCode(Integer code) {
  37. this.code = code;
  38. }
  39. public String getMessage() {
  40. return message;
  41. }
  42. public void setMessage(String message) {
  43. this.message = message;
  44. }
  45. public Map<String, Object> getData() {
  46. return data;
  47. }
  48. public void setData(Map<String, Object> data) {
  49. this.data = data;
  50. }
  51. public Result success(Boolean success) {
  52. this.setSuccess(success);
  53. return this;
  54. }
  55. public Result message(String message) {
  56. this.setMessage(message);
  57. return this;
  58. }
  59. public Result code(Integer code) {
  60. this.setCode(code);
  61. return this;
  62. }
  63. public Result data(String key, Object value) {
  64. this.data.put(key, value);
  65. return this;
  66. }
  67. public Result data(Map<String, Object> map) {
  68. this.setData(map);
  69. return this;
  70. }
  71. }

 JwtUtils代码如下

  1. package com.example.shop.utils;
  2. import io.jsonwebtoken.Claims;
  3. import io.jsonwebtoken.Jwts;
  4. import io.jsonwebtoken.SignatureAlgorithm;
  5. import java.util.Date;
  6. public class JwtUtils {
  7. // 7天过期,单位秒
  8. private static final long expire = 604800;
  9. // 32位秘钥
  10. private static final String secret = "abcdfghiabcdfghiabcdfghiabcdfghi";
  11. // 生成token
  12. public static String generateToken(String username) {
  13. Date now = new Date();
  14. Date expiration = new Date(now.getTime() + 1000 * expire);
  15. return Jwts.builder()
  16. .setHeaderParam("typ", "JWT") // 设置头部信息
  17. .setSubject(username) // 设置主题
  18. .setIssuedAt(now) // 设置签发时间
  19. .setExpiration(expiration) // 设置过期时间
  20. .signWith(SignatureAlgorithm.HS512, secret) // 设置签名使用的算法和秘钥
  21. .compact(); // 生成token
  22. }
  23. // 解析token,获取Claims
  24. public static Claims getClaimsByToken(String token){
  25. return Jwts.parser()
  26. .setSigningKey(secret) // 设置秘钥
  27. .parseClaimsJws(token) // 解析token
  28. .getBody(); // 获取token中的payload部分
  29. }
  30. }

 新建controller包,,在其下新建UserController

 UserController代码如下

  1. package com.example.shop.controller;
  2. import org.springframework.web.bind.annotation.*;
  3. import com.example.shop.utils.Result;
  4. import com.example.shop.utils.JwtUtils;
  5. import com.example.shop.bean.User;
  6. @RestController
  7. @RequestMapping("/user")
  8. @CrossOrigin
  9. public class UserController {
  10. @PostMapping("/login")
  11. public Result login(@RequestBody User user) {
  12. String token = JwtUtils.generateToken(user.getUsername());
  13. return Result.ok().data("token", token);
  14. }
  15. @GetMapping("/info")
  16. public Result info(@RequestParam String token) {
  17. String username = JwtUtils.getClaimsByToken(token).getSubject();
  18. String url = "https://img2.baidu.com/it/u=1325995315,4158780794&fm=26&fmt=auto&gp=0.ipg";
  19. return Result.ok().data("name", username).data("avatar", url);
  20. }
  21. @PostMapping("/logout")
  22. public Result logout() {
  23. return Result.ok();
  24. }
  25. }

添加依赖

 

  1. <dependency>
  2. <groupId>io.jsonwebtoken</groupId>
  3. <artifactId>jjwt</artifactId>
  4. <version>0.9.1</version>
  5. </dependency>

 运行localhost/user/login

输入和结果如下

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/769726
推荐阅读
相关标签
  

闽ICP备14008679号