簡體   English   中英

Spring:通過 Angular 應用程序授權標頭始終為空

[英]Spring: Authorization header is always null via Angular app

我正在使用SpringAngular構建一個應用程序,現在,我正在嘗試使用Spring security 和 (JWT)來實現安全階段
問題是當我從Angular Spring 發送Authorization 標頭時沒有收到它!
即使我確定它已經在請求中(來自 chrome 開發工具)。
同樣,當我從ARC(來自 Chrome 的高級 REST 客戶端)發送具有相同標頭的相同請求時,spring 會收到它並返回數據!
在 Angular 方面,我當然使用HttpInterceptor將令牌添加到請求中,如下所示:

export class HttpInterceptorService implements HttpInterceptor{
  private _api = `${environment.api}/api`;
  constructor(
    private _authService: AuthenticationService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{

    if(req.url.startsWith(this._api)){
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${this._authService.getToken()}`
        }
      });
    }
    
    return next.handle(req);
  }
}

在此處輸入圖片說明

這就是我在春季所做的事情:

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private List<String> excludedURLsPattern = Arrays.asList(new String[]{"/authenticate"});

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {

        return excludedURLsPattern
                .stream()
                .anyMatch(urlPattern -> request.getRequestURL().toString().contains(urlPattern));

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        System.out.println("=== request URL: "+request.getRequestURL());
        final String requestTokenHeader = request.getHeader("Authorization");
        System.out.println("=== requestTokenHeader: "+requestTokenHeader);// in this line I always get null (when using Angular not ARC) !!

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }

        // Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);

            // if token is valid configure Spring Security to manually set
            // authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the
                // Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }

}

這是我得到的消息:

2020-10-14 15:11:17.664  WARN 9856 --- [nio-5000-exec-1] c.s.c.security.config.JwtRequestFilter   : JWT Token does not begin with Bearer String

好的,我會把解決方案留在這里以防萬一有人需要它。
本博客中所述,並且由於我使用的是Sring Security,因此我必須在 Spring 安全級別啟用CORS

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...// this one right here
    }
}

暫無
暫無

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

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