当前位置: 首页 > backend >正文

【springsecurity oauth2授权中心】将硬编码的参数提出来放到 application.yml 里 P3

在application.yml里添加配置

application.yml

oauth2:client:id: clientsecret: secretauthentication-method: client_secret_basicgrant-types: authorization_code,refresh_tokenredirect-uris:- http://localhost:8081/login/oauth2/code/client- http://localhost:8081/login/oauth2/code/client2scopes: openid,userrequire-authorization-consent: truetoken:access-token-format: self_containedaccess-token-time-to-live: 2hserver:issuer-uri: http://localhost:9000

创建对应的配置类

如果用lombok没问题的话,可以选择lombok,我用lombok的@Data注解去自动生成getter, setter,idea里没有报错信息,但启动服务时报错,然后我就都给换成自己的写的getter,setter。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.time.Duration;
import java.util.List;@Component
@ConfigurationProperties(prefix = "oauth2")
public class OAuth2Properties {private Client client;private Token token;private Server server;public Client getClient() {return client;}public void setClient(Client client) {this.client = client;}public Token getToken() {return token;}public void setToken(Token token) {this.token = token;}public Server getServer() {return server;}public void setServer(Server server) {this.server = server;}
}class Client {private String id;private String secret;private String authenticationMethod;private List<String> grantTypes;private List<String> redirectUris;private List<String> scopes;private boolean requireAuthorizationConsent;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getSecret() {return secret;}public void setSecret(String secret) {this.secret = secret;}public String getAuthenticationMethod() {return authenticationMethod;}public void setAuthenticationMethod(String authenticationMethod) {this.authenticationMethod = authenticationMethod;}public List<String> getGrantTypes() {return grantTypes;}public void setGrantTypes(List<String> grantTypes) {this.grantTypes = grantTypes;}public List<String> getRedirectUris() {return redirectUris;}public void setRedirectUris(List<String> redirectUris) {this.redirectUris = redirectUris;}public List<String> getScopes() {return scopes;}public void setScopes(List<String> scopes) {this.scopes = scopes;}public boolean isRequireAuthorizationConsent() {return requireAuthorizationConsent;}public void setRequireAuthorizationConsent(boolean requireAuthorizationConsent) {this.requireAuthorizationConsent = requireAuthorizationConsent;}
}class Token {private String accessTokenFormat;private Duration accessTokenTimeToLive;public String getAccessTokenFormat() {return accessTokenFormat;}public void setAccessTokenFormat(String accessTokenFormat) {this.accessTokenFormat = accessTokenFormat;}public Duration getAccessTokenTimeToLive() {return accessTokenTimeToLive;}public void setAccessTokenTimeToLive(Duration accessTokenTimeToLive) {this.accessTokenTimeToLive = accessTokenTimeToLive;}
}class Server {private String issuerUri;public String getIssuerUri() {return issuerUri;}public void setIssuerUri(String issuerUri) {this.issuerUri = issuerUri;}
}

替换AuthorizationServerConfig类里硬编码的参数

注入配置类

private final OAuth2Properties oAuth2Properties;
publicAuthorizationServerConfig(OAuth2Properties oAuth2Properties) {this.oAuth2Properties = oAuth2Properties;
}

替换参数

@Beanpublic RegisteredClientRepository registeredClientRepository() {RegisteredClient.Builder clientBuilder = RegisteredClient.withId(UUID.randomUUID().toString()).clientId(oAuth2Properties.getClient().getId()).clientSecret(oAuth2Properties.getClient().getSecret()).clientAuthenticationMethod(new ClientAuthenticationMethod(oAuth2Properties.getClient().getAuthenticationMethod())).authorizationGrantTypes(grantTypes -> oAuth2Properties.getClient().getGrantTypes().forEach(gt -> grantTypes.add(new AuthorizationGrantType(gt))))
//                .redirectUri("http://localhost:8081/login/oauth2/code/client").scope(OidcScopes.OPENID).scopes(scopes -> scopes.addAll(oAuth2Properties.getClient().getScopes())).clientSettings(ClientSettings.builder().requireAuthorizationConsent(oAuth2Properties.getClient().isRequireAuthorizationConsent()).build()).tokenSettings(TokenSettings.builder().accessTokenFormat(OAuth2TokenFormat.SELF_CONTAINED).accessTokenTimeToLive(oAuth2Properties.getToken().getAccessTokenTimeToLive()).build());// 添加所有配置的重定向URIoAuth2Properties.getClient().getRedirectUris().forEach(clientBuilder::redirectUri);return new InMemoryRegisteredClientRepository(clientBuilder.build());}@Beanpublic AuthorizationServerSettings authorizationServerSettings() {return AuthorizationServerSettings.builder().issuer(oAuth2Properties.getServer().getIssuerUri()).build();}

多redirect_uri处理

一个授权中心,多个应用服务器的情况下,所有应用服务器都会来请求这一个授权中心进行授权拿权限,但每个应用服务器都有自己的域名,这就会产生多种redirect_uri的问题

上面配置文件里和代码中已经处理好了,具体改动如下

oauth2:client:redirect-uris:- http://localhost:8081/login/oauth2/code/client- http://localhost:8081/login/oauth2/code/client2
@Beanpublic RegisteredClientRepository registeredClientRepository() {RegisteredClient.Builder clientBuilder = RegisteredClient.withId(UUID.randomUUID().toString()).clientId(oAuth2Properties.getClient().getId()).clientSecret(oAuth2Properties.getClient().getSecret())// ...;// 添加所有配置的重定向URI
oAuth2Properties.getClient().getRedirectUris().forEach(clientBuilder::redirectUri);return new InMemoryRegisteredClientRepository(clientBuilder.build());}

测试

配置了两个回调地址,就可以使用如下两个链接来进行测试,结果都能正常拿到code

  • http://localhost:9000/oauth2/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8081/login/oauth2/code/client&scope=user
  • http://localhost:9000/oauth2/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8081/login/oauth2/code/client2&scope=user
http://www.xdnf.cn/news/1247.html

相关文章:

  • C++23 中 static_assert 和 if constexpr 的窄化布尔转换
  • Agent智能体ReAct机制深度解读:推理与行动的完美闭环
  • 实战华为1:1方式1 to 2 VLAN映射
  • hbuilderx云打包生成的ipa文件如何上架
  • 发送百度地图的定位
  • 7.6 GitHub Sentinel后端API实战:FastAPI高效集成与性能优化全解析
  • OpenCV中的透视变换方法详解
  • 【AI模型学习】Swin Transformer——优雅的模型
  • 【含文档+PPT+源码】基于微信小程序的健康饮食食谱推荐平台的设计与实现
  • 【微知】git reset --soft --hard以及不加的区别?
  • 入住刚装修好的新房,房间隔音太差应该怎么办?
  • Unity 带碰撞的粒子效果
  • OpenVINO教程(三):使用NNCF进行模型量化加速
  • MATLAB Coder 应用:转换 MATLAB 代码至 C/C++ | 实践步骤与问题解决
  • 【Pandas】pandas DataFrame truediv
  • 【程序员 NLP 入门】词嵌入 - 上下文中的窗口大小是什么意思? (★小白必会版★)
  • RESTful API 设计原则
  • 深度学习基石:神经网络核心知识全解析(一)
  • Curl用法解析
  • 前端频繁调用后端接口问题思考
  • 2025年4月22日(平滑)
  • 【Python笔记 03 】运算符
  • n8n更新1.87后界面报错Connection lost解决
  • 如何精准查询住宅IP?工具、方法与注意事项
  • HTML5+CSS3+JS小实例:CSS太阳动画特效
  • Java 静态内部类面试题与高质量答案合集
  • 源超长视频生成模型:FramePack
  • 丰富多样功能的小白工具,视频提取音频,在线使用,无需下载软件
  • Vscode指定缓存路径 .vscode 路径
  • net+MySQL中小民营企业安全生产管理系统(源码+lw+部署文档+讲解),源码可白嫖!