gpt4 book ai didi

angular - 请求表单 Angular 时,Spring Security Jwt Token 允许所有选项方法

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:24 25 4
gpt4 key购买 nike

我不知道怎么了,我到处上网查了,好像和我一样,但是我遇到了这个问题:

我正在使用 HttpClient 和 Angular 拦截器请求我的 Angular 应用程序到 setHeader,因为我的 Java Rest API 正在使用 JWT 进行身份验证并且需要 header 中的 token ,因此它将获取并验证用户请求,因为 Angular 拦截器不工作适本地。我在 Java 端得到 null 作为 token 并收到错误。请帮我解决这个问题。

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

Spring boot安全配置

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();



}
}

Angular 拦截器代码

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);
}
}

Angular 服务

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);
}
}

调用方法

public getAllUserList() {

console.log("I am calling");

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

})
}

浏览器网络

Network Tab

token 的本地存储

enter image description here

浏览器控制台错误消息

Browser Console

Spring Boot Java 控制台错误

backend Java Console Error

最佳答案

我认为您问题的正确答案在 JwtSecurityConfig 中。您需要添加 OPTIONS 调用以允许在不请求身份验证 token 的情况下通过 JWT 安全性。

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

http.csrf().disable()
.authorizeRequests()
// Add this line to your code
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("**/rest/**").authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(entryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

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



}

关于angular - 请求表单 Angular 时,Spring Security Jwt Token 允许所有选项方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54900325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com