SpringBoot整合JWT

JWT

(整合SpringBoot)

1. 引入依赖

<!--    引入JWT    -->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.4.0</version>
</dependency>

2. 编写工具类

public class JWTUtil {

    // 用于JWT进行签名加密的秘钥
    private static String SECRET = "code-duck-*%#@*!&";

    /**
     * @Param: 传入需要设置的payload信息
     * @return: 返回token
     */
    public static String generateToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        // 将map内的信息传入JWT的payload中
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        // 设置JWT令牌的过期时间为60
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60);
        builder.withExpiresAt(instance.getTime());

        // 设置签名并返回token
        return builder.sign(Algorithm.HMAC256(SECRET)).toString();
    }

    /**
     * @Param: 传入token
     * @return:
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * @Param: 传入token
     * @return: 解密的token信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}

3. 准备项目测试环境

编写controller>service>mapper

4. 获取Token

UserController.java

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String,String> login(@RequestParam("username")String username,
                                    @RequestParam("password")String password){

        HashMap<String, String> result = new HashMap<>();

        User user = userService.getUser(username);

        //返回用户为空,则说明此用户名信息不存在
        if (user==null){
            result.put("msg", "用户不存在");
            return result;
        }

        //判断密码是否正确
        if (!user.getPassword().equals(password)){
            result.put("msg", "密码错误");
            return result;
        }

        //验证通过
        HashMap<String, String> map = new HashMap<>();
        map.put("msg","success");
        map.put("username",username);
        map.put("role","admin");

        //生成token
        String token = JwtUtils.generateToken(map);

        result.put("token", token);

        return result;
    }

    @RequestMapping("/test")
    public String test(){

        return "请求成功!!!";
    }
}

5. 编写拦截器

JwtInceptor.java

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        HashMap<String, String> map = new HashMap<>();
        try {
            JwtUtils.verify(token);//验证令牌
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名!");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期!");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效!!");
        }
        map.put("code", "403");//设置状态
        //将 map 转为json  jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json); //前台返回数据
        return false;
    }
}

6. 注册MVC配置

JwtInterceptorConfig.java

@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JwtInterceptor()) //注册自定义拦截器
                .addPathPatterns("/**") //拦截所有路径
                .excludePathPatterns("/user/login"); //排除登陆请求
    }
}
posted @ 2020-12-06 23:29  juyss  阅读(1425)  评论(1编辑  收藏  举报