[英]spring boot security oauth2 preflight issue
I have problem with preflight in springboot security. 我在springboot安全性中有预检问题。 When I send request from postman all is ok but when I try to get the token from ts code I got this error 当我从邮递员发送请求时一切正常,但是当我尝试从ts代码获取令牌时,出现此错误
Response for preflight has invalid HTTP status code 403
I tried to resolve this problem by this solutions other solution on stack and spring doc 我试图通过此解决方案来解决此问题, 其他解决方案在堆栈和Spring文档
I don't know the problem is in ts or spring. 我不知道问题出在ts还是spring。 I put the code below: 我把下面的代码:
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);
}
and spring code 和弹簧代码
@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;
}
}
I'm new in spring security and I will be grateful for any help. 我是Spring Security的新手,我将不胜感激。
I put rest of spring security code because maybe there is an error. 我放入其余的Spring安全代码,因为可能有错误。 I was looking for answer in other similar stack post but neither of these solutions works in my problem. 我在其他类似的堆栈中寻找答案,但是这些解决方案都无法解决我的问题。
@Configuration
@EnableAuthorizationServer
public class Oauth2AuthServerConfig extends AuthorizationServerConfigurerAdapter{
private AuthenticationManager authenticationManager;
private DataSource dataSource;
@Autowired
public Oauth2AuthServerConfig(AuthenticationManager authenticationManager,
@Qualifier("dataSource") DataSource dataSource) {
this.dataSource = dataSource;
this.authenticationManager = authenticationManager;
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("clientpassword")
.scopes("read", "write")
.authorizedGrantTypes("password","authorization_code", "refresh_token")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(28*24*3600);
}
@Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); }
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
public class Oauth2ResourceServerConfig extends ResourceServerConfigurerAdapter{
private final DataSource dataSource;
@Autowired
public Oauth2ResourceServerConfig(@Qualifier("dataSource") DataSource dataSource) {
this.dataSource = dataSource;
}
@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("SELECT email, password, enabled FROM users WHERE email=?")
.authoritiesByUsernameQuery("SELECT * FROM users WHERE email=?");
//.passwordEncoder(passwordEncoder());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.authorizeRequests()
.antMatchers("/user/new").permitAll()
.anyRequest().authenticated().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable();
}
}
problem resolved I added 解决的问题我加了
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebSecurityConfig implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
response.setStatus(HttpStatus.NO_CONTENT.value());
}else{
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.