我正在开发一个 Spring-Boot 应用程序,我遇到的问题如下:
默认情况下,对我的 Controller 的每个请求都会重定向到/login,所以我不能那样使用它。
我可以通过设置禁用/login
security.oauth2.resource.filter-order = 3
在 application.properties 中。
但我想知道如何仅对非浏览器禁用它,这样我仍然可以使用登录。
编辑:
这就是我的方法:
http.antMatcher("/api/**")
.authorizeRequests().anyRequest().authenticated();
http.antMatcher("/**")
.formLogin();
从/api/运行的所有内容都是 REST,并且只能由 Oauth 处理。 其余的应该由登录处理。
但它仍然不起作用,我仍然收到重定向。
没关系,修好它。感谢 userWithLongNumber!
就我而言,事实证明我的 WebSecurity 配置错误。 现在可以了:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
formLogin().permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
我的 RessourceServerConfig 如下所示:
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.logout()
.logoutUrl("/oauth/logout")
.logoutSuccessHandler(customLogoutSuccessHandler)
.and()
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
最佳答案
您需要降低主应用程序安全过滤器的优先级。
如 Spring Boot 教程中所述。
The @EnableResourceServer annotation creates a security filter with @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER-1) by default, so by moving the main application security to @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) we can ensure that the rule for OAuth resource takes precedence.
设置
security.oauth2.resource.filter-order = 3
不会禁用主安全过滤器。它只是将其优先级更改为较低的值。 (负值优先级最高。-3 比 3 优先级高)
据我了解,您的问题是没有在 ResourceServerConfiguration 中正确设置匹配器。使其更具体如下。
http.antMatcher("/helloOAuth")
.authorizeRequests().anyRequest().authenticated();
https://github.com/lanka-guide/simple-oauth2-server有一个示例实现。可能会有所帮助。
关于java - Spring security Oauth 2 在/oauth/token上重定向行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649379/