我在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);
}
和spring代码
@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;
}
}
我是春季保安的新手,如果能帮上忙我会很感激。
发布于 2018-02-23 04:35:58
我放了spring安全代码的其余部分,因为可能有错误。我在其他类似的堆栈帖子中寻找答案,但这些解决方案都不能解决我的问题。
@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();
}
}
发布于 2018-02-23 06:57:13
问题已解决,我添加了
@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() {}
}
https://stackoverflow.com/questions/48915983
复制相似问题