我不知道怎么了,我到处都在线检查过,好像和我一样,但是我遇到了这个问题:
我正在请求将带有Angular拦截器的HttpClient与HttpClient一起使用的Angular应用程序设置为setHeader,因为我的Java Rest API使用JWT进行身份验证,并且在标头中需要令牌,因此它会获取并验证用户请求,因为Angular拦截器无法正常工作正确地。我在Java端将null作为令牌得到了一个错误。请帮助我。
最后,我发现它可能是春季安全性的问题,因为我调试并发现该选项请求所有过滤器,并且它没有标题,因此显示令牌并抛出异常 如果选项方法请求绕过并允许,那么可能是我的问题将会解决
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();
}
}
角度拦截器代码
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);
}
}
CallIng Mathod
public getAllUserList() {
console.log("I am calling");
this.service.getAllApiUsers()
.subscribe(data => {
this.alluser = data;
console.log(data);
})
}
浏览器网络
令牌的本地存储
浏览器控制台错误消息
Spring Boot Java Console错误
答案 0 :(得分:0)
角度拦截器看起来不错,但是在您的浏览器控制台中有CORS policy
错误。您的角度应用程序在端口4200
上运行,后端在8095
(不同的主机)上运行。
我不知道spring-boot
,但是在阅读了文档之后,您应该向后端应用程序添加一些cors策略(针对生产和开发环境而有所不同):
更多内容,请点击此处:https://spring.io/guides/gs/rest-service-cors/
现在您的对/allUser
的请求未发送...消除了CORS问题后,一切都应正常运行