springboot集成JWT生成token并自定义拦截器及解决拦截器失效问题

1.导入jwt依赖

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.10.3</version>
</dependency>

2.配置拦截

/**
 * WebMvcConfig配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(authenticationInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/user/login");
        }


    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        //拦截器
        return new AuthenticationInterceptor();
    }

}

3.自定义拦截器

@Component
public class AuthenticationInterceptor  implements HandlerInterceptor  {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>();
        try {
            JwtUtils.verifyToken(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效的签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","该令牌已过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","算法不匹配");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效!");
        }
        map.put("status",false);
        String errorMsg = JSONObject.toJSONString(map);
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(errorMsg);
        writer.close();
        return false;
    }
}

4.添加@component是会报The bean ‘xxx’, defined in class path resource [com/uniedu/frame/swagger2/Swagger2Configuration.class], could not be registered. A bean with that name has already been defined in class path resource

5.解决方法

 

main:
  allow-bean-definition-overriding: true

6.测试

@PostMapping("/login")
@ResponseBody
private Msg getToken(@RequestBody Msg msg){
    HashMap<String, String> claim = new HashMap<>();
    claim.put("id","PVor7HsCjhtwmmrewNrXh9UeO2zy4pWZ");
    claim.put("username","住户1");
    return new Msg().success(JwtUtils.getToken(claim));
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值