使用 spring 拦截器和自定义注解进行接口鉴权、登录校验

项目中涉及到接口鉴权和登录超时判断等校验,所以研究下强大spring的拦截器功能,如下转载、学习几篇不错博文,在此先谢过原作者的分享。

https://www.jianshu.com/p/97362fdf039e
http://www.scienjus.com/restful-token-authorization/

一、写注解

编写一个自定义注解:用于需要鉴权或者登录校验功能的接口(方法上)

/**
 * 在需要登录验证的Controller的方法上使用此注解
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}

ElementType.MeTHOD表示该自定义注解可以用在方法上
RetentionPolicy.RUNTIME 表示该注解在代码运行时起作用

二、写登录拦截器

自定义拦截器需实现HandlerInterceptor接口

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解,需要认证
        if (methodAnnotation != null) {
            // 执行认证
            String token = request.getHeader("token");  // 从 http 请求头中取出 token
            if (token == null) {
                throw new RuntimeException("无token,请重新登录");
            }
            int userId;
            try {
                userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));  // 获取 token 中的 user id
            } catch (JWTDecodeException e) {
                throw new RuntimeException("token无效,请重新登录");
            }
            User user = userService.findById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在,请重新登录");
            }
            // 验证 token
            try {
                JWTVerifier verifier =  JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    verifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("token无效,请重新登录");
                }
            } catch (UnsupportedEncodingException ignore) {}
            request.setAttribute("currentUser", user);
            return true;
        }
        return true;
    }

token 的验证过程和 token 的生成过程有关,在用户登录接口中,我使用的是用户的密码左右 token 的密钥进行加密(因为服务器并没有对 token 进行存储,所以加密的密钥最好是一个用户更改密码之后会变的东西,我就直接用密码了),还将 user id 存到了 JWT token 的 audience 中,因此我们能够从 token 中知道用户是谁。具体的JWT token 的生成和验证过程可以看看我们项目中使用的 jar 包的文档

三、配置拦截器

spring boot 有很多默认配置,如果要添加拦截器之类的,就新建配置类并继承 WebMvcConfigurerAdapter 类,Override
相应的方法,来看看怎么添加我们刚刚编写好的拦截器

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**");    // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
        super.addInterceptors(registry);
    }

    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

注:token的读写可以使用持久化或缓存技术辅助,http://www.scienjus.com/restful-token-authorization/ 这篇文章使用spring data redis介绍的通俗易懂。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值