【问题标题】:401 Unauthorized for Options request to /oauth/token in spring401 Unauthorized for Options request to /oauth/token in spring
【发布时间】:2017-10-22 05:42:08
【问题描述】:

我正在使用 spring boot 来制作 rest api 并使用 spring security oauth2 进行登录身份验证。当我从与 spring boot 集成的角度客户端向 localhost:8080/oauth/token 发送请求时,它工作正常。(运行在同一个本地主机上:8080)。 但是如果我想从在 localhost(xampp) 上运行的客户端登录,那么它会给出错误

更新:我也在 application.java 文件中保存了这段代码

@SpringBootApplication
public class Application {
private static final String[] REQUEST_METHOD_SUPPORTED = { "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD" };

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init() {
    return (args) -> {
        FileSystemUtils.deleteRecursively(new File(FileUploadController.ROOT));

        Files.createDirectory(Paths.get(FileUploadController.ROOT));
    };
}
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
            .allowedOrigins("localhost:80")
            .allowedMethods("POST", "GET", "PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2");

        }
    };
 }


}

OAuth2ServerConfiguration.java

@Configuration
@EnableWebSecurity
public class OAuth2ServerConfiguration {

private static final String RESOURCE_ID = "restservice";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
        ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        // @formatter:off
        resources
            .resourceId(RESOURCE_ID);
        // @formatter:on
    }
    @Order(-1)
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http

            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()

        // @formatter:on
    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
        AuthorizationServerConfigurerAdapter {

    private TokenStore tokenStore = new InMemoryTokenStore();

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        // @formatter:off
        endpoints
            .tokenStore(this.tokenStore)
            .authenticationManager(this.authenticationManager)
            .userDetailsService(userDetailsService);                            

        // @formatter:on
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // @formatter:off
        clients
            .inMemory()
                .withClient("clientapp")
                    .authorizedGrantTypes("password", "refresh_token")
                    .authorities("USER")
                    .scopes("read", "write")
                    .resourceIds(RESOURCE_ID)
                    .secret("LMS");
        // @formatter:on
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(this.tokenStore);
        return tokenServices;
    }

}

}

我已经检查并尝试了许多解决方案,但无法弄清楚。请帮助!!!!

【问题讨论】:

  • 添加一个CORS过滤器并让OPTIONS绕过过滤器
  • 查看更新的问题 plz.. 是否足以绕过?

标签: java angularjs spring spring-mvc oauth


【解决方案1】:

选项请求会自动发送以确保服务器处于活动状态,因此如果您使用“WebSecurityConfgurerAdapter”,您需要在安全配置中允许选项方法

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

         httpSecurity.// your autherization configuration
          .antMatchers(HttpMethod.OPTIONS).permitAll()


 } 

【讨论】:

  • http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS,"**").permitAll() .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
  • 尝试不使用 '**' antMatchers(HttpMethod.OPTIONS)
【解决方案2】:

看起来您根据请求传递了一些客户标头,您可以看到有关 CORS 的基本概念here

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("POST", "GET", "PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2");
        }
}

或者你只是配置

config.addAllowedHeader("*");
config.addAllowedMethod("*");

请根据此覆盖您的 addCorsMappings 并在此方法中添加更新您的标头(如果您传递任何内容)。

【讨论】:

  • 我已经尝试了所有人推荐的所有这些东西,但没有任何效果。
  • 请你做两件事我正在更新我的答案
  • .anyRequest().permitAll() 添加此项以确认
  • 您在哪个端口运行 angularjs 应用程序?
  • 我已经尝试过 this.notworking.actually 其他端点可以通过提供相同的标头来访问,但是这个登录端点 /oauth/token 这不起作用。不知道为什么
【解决方案3】:

在使用 oidc-client 和 vuejs 实现 spring-security oauth2 时遇到了类似的问题。所以我发现客户端应用程序必须通过 oidc-client 库不支持的基本身份验证发送到服务器。解决方法是允许客户端进行表单身份验证,如下所示:

@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.allowFormAuthenticationForClients();
  }
}

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2011-03-11
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多