【问题标题】:spring boot security oauth2 preflight issue春季启动安全oauth2预检问题
【发布时间】:2018-08-01 15:05:21
【问题描述】:

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

Response for preflight has invalid HTTP status code 403

我试图通过这个解决方案来解决这个问题 other solution on stackspring 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


【解决方案1】:

问题已解决 我加了

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

【讨论】:

    【解决方案2】:

    我放了其余的 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-09-11
      • 2015-04-17
      • 2017-06-24
      • 2015-07-25
      • 2016-06-29
      • 2017-07-03
      • 2017-10-22
      • 2020-09-27
      • 1970-01-01
      相关资源
      最近更新 更多