【发布时间】:2018-08-01 15:05:21
【问题描述】:
我在 springboot 安全性中遇到了预检问题。当我从邮递员发送请求时一切正常,但是当我尝试从 ts 代码获取令牌时出现此错误
Response for preflight has invalid HTTP status code 403
我试图通过这个解决方案来解决这个问题 other solution on stack 和 spring doc
我不知道问题出在 ts 还是 spring。我把代码放在下面:
constructor(private http: Http) { }
public login(email, password) {
const params = new URLSearchParams();
params.append('username', email);
params.append('password', password);
params.append('grant_type', 'password');
let headers = new Headers({'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
'Access-Control-Allow-Credentials': true ,
'Content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa("client:clientpassword")});
const options = new RequestOptions({ headers: headers });
console.log('http://localhost:1818/oauth/token', params.toString(), options);
return this.http.post('http://localhost:1818/oauth/token', params.toString(), options);
}
和弹簧代码
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("/**");
}
};
}
}
@EnableWebSecurity
public class MyConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
//other config
}
@Bean
CorsConfigurationSource corsConfigurationSource()
{
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("/**"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
我是 Spring Security 的新手,如果能提供任何帮助,我将不胜感激。
【问题讨论】:
-
当然,第二类的名称与第一类不同。我贴错了。
标签: java spring security oauth-2.0