其他分享
首页 > 其他分享> > springboot 拦截器解决authorization为null

springboot 拦截器解决authorization为null

作者:互联网

本项目为前后端分离,接口采用springboot2+mybatis方式,前端header携带authorization参数请求接口,有些接口不需要携带authorization,本人初搞java,在研究了老半天后如下的方式解决了我的问题,在拦截器里拿到了我要的authorization,相关配置代码如下:

一、创建拦截器配置

#### 原代码如下,这种拿不到authorization:
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
    //注册拦截器
    ## 新旧写法区别就在这里
    InterceptorRegistration registration = registry.addInterceptor(new AuthorizationInterceptor());  

    registration.addPathPatterns("/**");
    registration.excludePathPatterns(
            "/api/Base_User/UserLogin",
            "/api/Base_User/GetCode",
            "/api/Base_PT_Type/GetDataList",
            "/api/Base_User/UserInfoByToken",
            "/**/*.html",
            "/**/*.js",
            "/**/*.css",
            "/**/*.woff",
            "/**/*.ttf"
      );
   }
}

#### 新代码 增加getInterceptor() 
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
//让bean提前加载
@Bean
public HandlerInterceptor getInterceptor(){
    return new AuthorizationInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    //注册拦截器
    InterceptorRegistration registration = registry.addInterceptor(getInterceptor());
    registration.addPathPatterns("/**");
    registration.excludePathPatterns(
            "/api/Base_User/UserLogin",
            "/api/Base_User/GetCode",
            "/api/Base_PT_Type/GetDataList",
            "/api/Base_User/UserInfoByToken",
            "/**/*.html",
            "/**/*.js",
            "/**/*.css",
            "/**/*.woff",
            "/**/*.ttf"
    );
  }
}

二、拦截器

public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
        response.setStatus(HttpServletResponse.SC_OK);
        return true;
    }

    String authorization = request.getHeader("authorization");
    if (StringHelper.isEmpty(authorization)){
        return false;
    }
    String userid= TokenUtils.verify(authorization.replace("Bearer ",""));
    if (StringHelper.isEmpty(userid)){
        ResponseModel dataobj=new ResponseModel(0,false,"token无效");

        return false;
    }
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
 }
}

标签:Base,拦截器,springboot,api,registration,null,public,authorization
来源: https://www.cnblogs.com/frank2828/p/15434294.html