简体   繁体   English

Angular post-call 作为 OPTIONS 提交给 springboot

[英]Angular post-call submitted as OPTIONS to springboot

I am developing end to end application UI Angular, Backend Spring boot with JWT Token.我正在使用 JWT 令牌开发端到端应用程序 UI Angular、后端 Spring 启动。

It reaches my method jwtFilter from Postman and angular.它从邮递员和角度到达我的方法 jwtFilter 。

After the jwtFilter my postman request reaches createJWTtoken method在 jwtFilter 我的邮递员请求到达 createJWTtoken 方法之后

From angular it doesn't reach create a token method, it returns 200 OK response.从角度来看,它没有达到创建令牌方法,它返回 200 OK 响应。

Angular submitting my request as OPTIONS Angular 将我的请求作为选项提交

Angular log角度日志

config.JwtRequestFilter    : JWT Token does not begin with Bearer String
DispatcherServlet        : ***OPTIONS*** "/myapp/authenticate", parameters={}
RequestMappingHandlerMapping : Mapped to com.myapp.controller.JwtAuthenticationController#createAuthenticationToken(JwtRequest)
DispatcherServlet        : Completed 200 OK

Request from postman log来自邮递员日志的请求

config.JwtRequestFilter    : JWT Token does not begin with Bearer String
DispatcherServlet        : ***POST*** "/myapp/authenticate", parameters={}
RequestMappingHandlerMapping : Mapped to com.myapp.controller.JwtAuthenticationController#createAuthenticationToken(JwtRequest)
RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [com.myapp.model.security.JwtRequest@8d233a8]
JwtAuthenticationController      : Creating jwt token
StatisticsImpl         : HHH000117: HQL: select generatedAlias0 from Users as generatedAlias0 where generatedAlias0.userName=:param0, time: 297ms, rows: 1
HttpEntityMethodProcessor  : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json, application/x-jackson-smile, application/cbor]
HttpEntityMethodProcessor  : Writing [com.myapp.model.security.JwtResponse@2127c1d5]
DispatcherServlet        : Completed 200 OK

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

    final String requestTokenHeader = request.getHeader("Authorization");

    String username = null;
    String jwtToken = null;
    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");
    }
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
    chain.doFilter(request, response);//Both postman and angular reach this point.
}**
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                .authorizeRequests().antMatchers("/authenticate", "/myapp/authenticate").permitAll().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated().and().
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        }

Angular post-call角后呼叫

public baseUrl = 'http://localhost:8081/myapp/authenticate';

  public callService(userInfo:User){
    var username=userInfo.username;
    var password = userInfo.password;
    return this.http.post(this.baseUrl,
    {
      'username': username,
    'password': password
    },
    { headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Access-Control-Allow-Origin',
    }), observe: 'response'}
    ).pipe(
      map(userData => {
        sessionStorage.setItem("username", username);
        let tokenStr = "Bearer " + '';
        console.log(tokenStr);
        sessionStorage.setItem("token", tokenStr);
        return userData;
      })
    );
  }

proxy.config.json proxy.config.json

{
"/api": {
  "target": "http://localhost:8080/",
  "changeOrigin": true,
  "secure": false,
  "pathRewrite": {
  "^/api": ""
}
 }
}

That's not angular that post a preflight OPTIONS request, it's your browser.这不是发布预检 OPTIONS 请求的角度,而是您的浏览器。 Check this Angular $http is sending OPTIONS instead of PUT/POST检查这个Angular $http 正在发送 OPTIONS 而不是 PUT/POST

Conclusion you have to fix the CORS policy in the spring boot and how the spring boot handle the options request in your SecurityConfiguration.结论您必须修复 Spring Boot 中的 CORS 策略以及 Spring Boot 如何处理 SecurityConfiguration 中的选项请求。 Can you please add this part of the code in your question.您能否在您的问题中添加这部分代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM