Spring Boot OAuth2 2.0.0.RELEASE中如何禁用授权端点?
禁用Spring Boot OAuth2 2.0.0.RELEASE的授权端点,仅保留令牌端点
嘿,这个需求完全可以实现!针对你使用的Spring Boot OAuth2 2.0.0.RELEASE版本,这里有两种可靠的配置方式来禁用授权端点(/oauth2/authorize),同时保留令牌端点(/oauth2/token)的正常使用:
方式一:通过配置文件快速禁用
在你的application.yml或application.properties中添加以下配置,直接关闭授权端点的启用状态:
使用application.yml
spring: security: oauth2: authorization-server: endpoint: authorize: enabled: false
使用application.properties
spring.security.oauth2.authorization-server.endpoint.authorize.enabled=false
配置生效后,任何访问/oauth2/authorize的请求都会被拒绝,而令牌端点依然可以正常处理获取令牌的请求。
方式二:通过Java代码自定义配置
如果你需要更灵活的控制,可以通过编写Spring Security配置类来实现:
@Configuration @EnableWebSecurity public class AuthorizationServerSecurityConfig { @Bean public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { // 应用授权服务器的默认安全配置 OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); // 明确禁用授权端点的访问 http.authorizeHttpRequests(authorizeRequests -> authorizeRequests .requestMatchers("/oauth2/authorize").denyAll() .anyRequest().authenticated() ); return http.build(); } // 请确保你已经配置了必要的Bean,比如RegisteredClientRepository、ClientRegistrationRepository等 }
或者,你也可以直接在OAuth2AuthorizationServerConfigurer中配置端点的启用状态:
@Bean public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); // 禁用授权端点 authorizationServerConfigurer.authorizationEndpoint(endpoint -> endpoint.enabled(false)); // 应用配置并构建安全链 http.apply(authorizationServerConfigurer); http.formLogin(Customizer.withDefaults()); // 如果需要表单登录支持 return http.build(); }
这两种Java配置方式都能达到同样的效果,你可以根据自己的代码风格选择合适的方式。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

