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 {
 }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM