首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >spring boot安全oauth2印前检查问题

spring boot安全oauth2印前检查问题
EN

Stack Overflow用户
提问于 2018-02-22 05:43:27
回答 2查看 545关注 0票数 0

我在springboot的安全检查中遇到了问题。当我从邮递员那里发送请求时,一切正常,但是当我尝试从ts代码中获取令牌时,我得到了这个错误

代码语言:javascript
运行
复制
Response for preflight has invalid HTTP status code 403

我试图通过这个解决方案other solution on stackspring doc来解决这个问题

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

代码语言:javascript
运行
复制
    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代码

代码语言:javascript
运行
复制
@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;
    }
}

我是春季保安的新手,如果能帮上忙我会很感激。

EN

回答 2

Stack Overflow用户

发布于 2018-02-23 04:35:58

我放了spring安全代码的其余部分,因为可能有错误。我在其他类似的堆栈帖子中寻找答案,但这些解决方案都不能解决我的问题。

代码语言:javascript
运行
复制
@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();
    }




}
票数 0
EN

Stack Overflow用户

发布于 2018-02-23 06:57:13

问题已解决,我添加了

代码语言:javascript
运行
复制
    @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() {}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48915983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档