我正在尝试从具有Spring安全后端的Angular 7执行登录:
login(username: string, password: string) {
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
return this.http.post<UserInfo>(`${API_URL}/login`, formData, {observe: 'response'})
.pipe(map(response => {
const jwtToken = response.headers.get(AUTHORIZATION).replace('Bearer', '').trim();
const userInfo = response.body;
if (jwtToken && userInfo) {
const user = new User(username, password, jwtToken, userInfo);
localStorage.setItem(CURRENT_USER, JSON.stringify(user));
this.currentUserSubject.next(user);
}
return response;
}));
}
但是,response.headers只是空的,不包含任何标题。 Postman和Chrome开发人员工具显示了许多标头,甚至是我需要的标头-授权。我已经审查了许多SO问题和github问题,但是他们都说相同的话,这对我不起作用-只是在CORS Access-Control-Expose-Headers中列出了头,但是我做到了,没有任何改变。这是相关的Spring配置:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:4200");
configuration.addExposedHeader("Authorization");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
在这一点上,我陷入困境,不知道如何使Angular访问这些标头:
答案 0 :(得分:2)
您需要authorization header
,可以通过response.headers.get("Authorization")
获得。试试:
const jwtToken = response.headers.get("Authorization").replace('Bearer', '').trim();
答案 1 :(得分:0)
在服务器端,您需要配置“ Access-Control-Allow-Headers”。请参阅这篇文章:Angular 6 Get response headers with httpclient issue。
对我来说,这种配置可以达到目的:
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addExposedHeader(
"Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, "
+ "Content-Type, Access-Control-Request-Method, Custom-Filter-Header");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return source;
}