spring boot security oauth2 preflight问题

时间:2018-02-21 21:43:27

标签: java spring security oauth-2.0

我在springboot安全性方面遇到预检问题。当我从邮递员发送请求时,一切正常,但是当我尝试从ts代码获取令牌时,我收到了此错误

Response for preflight has invalid HTTP status code 403

我尝试通过此解决方案解决此问题 other solution on stackspring doc

我不知道问题出在问题还是春天。我把代码放在下面:

    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;
    }
}

我是春天安全的新人,我将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:0)

我把其余的春季安全码放在一边,因为可能有错误。我在其他类似的堆栈帖子中寻找答案,但这些解决方案都不适用于我的问题。

@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();
    }




}

答案 1 :(得分:0)

问题解决了 我添加了

    val orderFlow: Flow[String, String, NotUsed] = {
        val (sink, source) = MergeHub.source[String](16)
            .toMat(BroadcastHub.sink(256))(Keep.both).run()
        Flow.fromSinkAndSource(sink, source)
    }