Spring OPTION请求返回401与Angular

时间:2017-10-26 11:31:00

标签: angularjs spring spring-security oauth-2.0 cors

我尝试在Spring中使用Oauth2实现webSecurityService。我正在使用Spring Boot和Angular4客户端的rest API。我刚刚完成了我的API部分并在postman中进行了测试:

public class WebSecurityConfig extends WebMvcConfigurerAdapter {

@Configuration
protected static class UserDetailsSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

}

@Configuration
@EnableResourceServer
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ClientService appClientsUserDetailsService;

    @Autowired
    UserService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(appClientsUserDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

}

enter image description here

一切正常,但当我尝试在Angular4客户端中实现我的authService时,我尝试连接时出现此错误:

  

zone.js:2933选项http://localhost:8081/oauth/token?username=user1&password=password1&grant_type=password&scope=read 401()   登录:1无法加载http://localhost:8081/oauth/token?username=user1&password=password1&grant_type=password&scope=read:预检的响应具有无效的HTTP状态代码401

这是由于Angular Option请求,但我不明白如何授权OPTION类型请求。如果你有任何关于它的信息。

感谢。

0 个答案:

没有答案