springboot+jwt实现token认证

首先编写拦截器,拦截请求

@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在请求被处理之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 检查每个到来的请求对应的session域中是否有登录标识
        String token = request.getHeader("Authorization");
        boolean success = TokenUntils.verifyToken(token);
        System.out.println("Authorization : " + token + " 验证: " + success);
        return success;
    }

    /**
     * 在请求被处理后,视图渲染之前调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束后调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

之后编写config 注册拦截器 拦截除/login以外所有请求

@Configuration
public class LoginConfig implements WebMvcConfigurer {

    @Autowired
    LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration loginRegistry = registry.addInterceptor(loginInterceptor);
        // 拦截路径
        loginRegistry.addPathPatterns("/**");
        // 排除路径
        loginRegistry.excludePathPatterns("/login");
        //loginRegistry.excludePathPatterns("/image/login/*.png");
    }
}

tokenUntils

public class TokenUntils {
    public static String createToken(String code){
        String token = "";
        token = JWT.create()
                .withAudience(code)
                .withExpiresAt(new Date(System.currentTimeMillis() + staticContext.expiresTime))
                .sign(Algorithm.HMAC256(staticContext.SECRET));
        return token;
    }

    public static boolean verifyToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(staticContext.SECRET)).build();
        try{
            jwtVerifier.verify(token);
            return true;
        }catch (Exception e) {
            System.out.println("验证token出错");
            return false;
        }
    }
}

其中,.withAudience(code)可以不填,也可以添加其他信息

你可能感兴趣的:(springboot,jwt)