使用拦截器,统一的鉴权处理?

使用拦截器,统一的鉴权处理?,第1张

定义拦截器的方法:

1.实现HandlerInterceptor

2.重写preHandle

      /**
     * 前置处理
     */

  

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        //1、获取请求头
        String token = request.getHeader("Authorization");

        //2、使用工具类,判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        //3、如果token失效,返回状态码401,拦截
        if(!verifyToken) {
            response.setStatus(401);
            return false;
        }
       // 4、如果token正常可用,放行
        //解析token,获取id和手机号码,构造User对象,存入Threadlocal
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");

        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHolder.set(user);

        return true;
    }


     //清空
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       UserHolder.remove();
    }
}

 

配置拦截器:

实现WebMvcConfigurer

重写addInterceptor

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig  implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(new String[]{"/user/login","/user/loginVerification"});
    }
}
  工具类: 实现向ThreadLocal存储数据的方法:
public class UserHolder {

    private static ThreadLocal tl = new ThreadLocal<>();


    //将用户对象,存入Threadlocal
    public static void set(User user) {
        tl.set(user);
    }

    //从当前线程,获取用户对象
    public static User get() {
        return tl.get();
    }

    //从当前线程,获取用户对象的id
    public static Long getUserId() {
        return tl.get().getId();
    }

    //从当前线程,获取用户对象的手机号码
    public static String getMobile() {
        return tl.get().getMobile();
    }
    //清空
     public static void remove(){
     tl.remove();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/905007.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存