Spring Security Jwt Token在请求表单角度时允许所有Options方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Security Jwt Token在请求表单角度时允许所有Options方法相关的知识,希望对你有一定的参考价值。

我不知道出了什么问题,我在网上到处检查,看起来和我一样,但是我遇到了这个问题:

我正在使用HttpClient和Angular拦截器向SetHeader请求My Angular应用程序,因为我的Java Rest API正在使用JWT进行身份验证,并且在标头中需要一个令牌,因此它将获取并验证用户请求,因为Angular拦截器无法正常工作。我在Java端获取null作为标记并出现错误。请帮我解决一下这个。

最后我发现它可能是spring security的问题,因为我调试并发现选项请求所有过滤器并且它没有头,所以它显示令牌并抛出异常,如果选项方法请求绕过并允许那么可能是我的问题将解决

Spring启动安全配置

package com.techprimers.security.jwtsecurity.config;

import com.techprimers.security.jwtsecurity.security.JwtAuthenticationEntryPoint;
import com.techprimers.security.jwtsecurity.security.JwtAuthenticationProvider;
import com.techprimers.security.jwtsecurity.security.JwtAuthenticationTokenFilter;
import com.techprimers.security.jwtsecurity.security.JwtSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Collections;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private JwtAuthenticationProvider authenticationProvider;
    @Autowired
    private JwtAuthenticationEntryPoint entryPoint;

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Collections.singletonList(authenticationProvider));
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter() {
        JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
        return filter;
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeRequests().antMatchers("**/rest/**").authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(entryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.headers().cacheControl();



    }
}

角度拦截器代码

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available



            console.log("i am inside");

            request = request.clone({
                setHeaders: {
                    Accept: 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`
                }
            });


        return next.handle(request);
    }
}

角度服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {

  constructor(private http: HttpClient) { }

  api_user_url = 'http://localhost:8095';

  getAllApiUsers(): Observable<any> {
    return this.http.get(this.api_user_url + "/allUser");
  }

  setUserLogin(obj):Observable<any>{

    return this.http.post(this.api_user_url +"/login", obj);
  }
}

CallIng方法

public getAllUserList() {

    console.log("I am calling");

    this.service.getAllApiUsers()
      .subscribe(data => {
        this.alluser = data;
        console.log(data);

      })
  }

浏览器网络

Network Tab

令牌的本地存储

enter image description here

Browser Console错误消息

Browser Console

Spring Boot Java控制台错误

backend Java Console Error

答案

角度拦截器看起来不错,但在浏览器控制台中有CORS policy错误。您的角应用程序在端口4200上运行,您的后端在8095(不同的主机)上运行。

我不知道spring-boot,但在审阅文档后,您应该在后端应用程序中添加一些cors策略(对于生产和开发环境而言不同):

enter image description here

更多你可以在这里阅读:https://spring.io/guides/gs/rest-service-cors/

现在你的/allUser请求没有发送...删除CORS问题后,一切都应该正常工作

以上是关于Spring Security Jwt Token在请求表单角度时允许所有Options方法的主要内容,如果未能解决你的问题,请参考以下文章

后端架构token授权认证机制:spring security JSON Web Token(JWT)简例

redis jwt spring boot spring security 实现api token 验证

完成 - Spring Security JWT Token_Key

spring security 的jwt认证以及原理解析

spring security 的jwt认证以及原理解析

Spring Security 整合 JSON Web Token(JWT)