簡體   English   中英

如何修復 Spring 安全授權 header 未通過?

[英]How to fix Spring Security Authorization header not being passed?

在我的 REST 服務之一中,我使用 Spring 安全性來驗證在 header 中傳遞的令牌。 但是,spring 無法找到“授權”header,即使它在那里。 在測試中甚至在本地進行測試時,這不是問題,但是當我們部署到 PROD 時,我們遇到了這個問題。

作為替代/解決方法,我刪除了 Spring 安全性,而是嘗試在實際端點中驗證我的令牌,然后繼續使用請求的 rest,如下所示:

@PostMapping(value="/create",consumes="application/json; charset=utf-8")
    @CrossOrigin
    public ResponseEntity createAccount(@RequestBody MerchantAccount merchantAccount,@RequestHeader(name="Authorization") String token) {
        log.info("Checking User Token");
        if(!jwtUtil.isAuthorizedToken(token))
            return ResponseEntity.status(401).build();
//some creating Account Logic
}

如果我再次執行上述操作,它將在 TEST 和 LOCAL 中有效,但在 PROD 中無效。 我會回來的錯誤是“缺少授權標頭”。 但它又一次出現了。 (測試從 postman 到)。

經過一番研究,我發現我可以添加“,required=false”,這樣 spring 就不會檢查它,但是仍然沒有要提取的令牌。

PROD 和 TEST 與我的本地之間的唯一區別如下:

Java 版本 java 版本正在測試: java version "1.6.0_32"

PROD 上的 java 版本: java version "1.8.0_121"

java 本地版本: java version "1.8.0_221"

在測試中,我們使用 HTTP 和 PROD 它是 HTTPS。 POM 文件中的 Spring 安全版本為 5.2

編輯在我的 web 配置中,我確實有一個部分允許“授權”header 出現,如下所示。

 @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));//YOLO Allow all origins, we can change this once we go to prod
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS"));//Allowed Methods
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type","Access-Control-Request-Headers","Access-Control-Request-Method",
               "Accept","Access-Control-Allow-Headers"));//Allowed Headers
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

當我遍歷請求過濾器中的標頭時更新測試和本地(如下所示)

@Component
@Service
public class JwtRequestFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        logger.info("Done Getting Headers");
        Collections.list(request.getHeaderNames()).forEach(item -> logger.info("header name is " + item));
        logger.info("Done Getting Headers");
        boolean isAccessToken = true;
        final String requestTokenHeader = request.getHeader("authorization");//This is null as the Authorization header is not found in request
}

我得到以下 output。 測試和本地

工作測試

在 PROD 上,我得到以下信息:

產品結果

請幫忙。

在流浪星系之后......

我已經用這個修復了它:

@Configuration
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and() /*.other stuff */;
    }
}

基本上,您需要使用http object 啟用cors() ..然后有多種方法可以為每個控制器/方法或全局處理 cros 來源。

我的問題是這樣的:

每當我從 postman 發出請求時,它都會起作用,並且 header 中的"Authorization"鍵始終存在,就像您一樣使用請求過濾器對其進行調試。

但是,每次從前端應用程序(反應)發出請求時,瀏覽器每次都會阻止"Authorization"鍵......

要全局配置它:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry
                  .addMapping("/greeting-javaconfig")
                  .allowedOrigins("http://localhost:8080");
        }
    };
}

或者,controller級別,

@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/greeting")
public String greeting() {
    return "works!";
}

參考:

SO回答Spring官方指南

可能的問題:

  • 在公開的標頭中設置授權,允許的標頭列表
  • setAllowedMethods中設置OPTIONS方法

當使用Spring SecuritySpring web 通量時,我必須使用以下配置才能使其工作:-

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@EnableWebFluxSecurity
public class WebSecurityConfig {

  @Bean
  public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

    http.cors().and()
        .csrf().disable()
        .authorizeExchange()
        .pathMatchers("/**").permitAll()
        .anyExchange()
        .authenticated()
        .and()
        ... //more mappings 

    return http.build();
  }

  @Bean
  CorsConfigurationSource corsConfiguration() {
    CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.applyPermitDefaultValues();
    UrlBasedCorsConfigurationSource source =
        new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfig);
    return source;
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM