新年開箱 | Spring Authorization Server 全新的授權服務器上手

前言
Spring Authorization Server 是 Spring 團隊最新開發(fā)適配 OAuth 協(xié)議的授權服務器項目,旨在替代原有的 Spring Security OAuth
經(jīng)過半年的開發(fā)和孵化,目前已經(jīng)發(fā)布了 0.1.0 版本,初步支持授權碼、客戶端、刷新、注銷等 OAuth 協(xié)議
本文環(huán)境基于 Spring Boot 2.4.2 && authorization-server 0.1.0
Server 搭建
1. maven 依賴
<dependency>
??<groupId>org.springframework.security.experimentalgroupId>
??<artifactId>spring-security-oauth2-authorization-serverartifactId>
??<version>0.1.0version>
dependency>
<dependency>
??<groupId>org.springframework.bootgroupId>
??<artifactId>spring-boot-starter-securityartifactId>
dependency>
2. 初始化配置
由于官方還未提供對應的 Spring Boot Starter 自動化配置,需要自己配置相關的 @Bean 本配置基于 Spring Boot 2.4.2 請知悉
@Configuration
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
public?class?AuthServerConfiguration?{
?//??定義?spring?security?攔擊鏈規(guī)則
?@Bean
?SecurityFilterChain?defaultSecurityFilterChain(HttpSecurity?http)?throws?Exception?{
??http
????.authorizeRequests(authorizeRequests?->
??????authorizeRequests.anyRequest().authenticated()
????)
????.formLogin(withDefaults());
??return?http.build();
?}
??//?創(chuàng)建默認登錄用戶?lengleng?/?123456
?@Bean
?public?UserDetailsService?userDetailsService()?{
??UserDetails?userDetails?=?User.builder()
????.username("lengleng")
????.password("{noop}123456")
????.authorities("ROLE_USER")
????.build();
??return?new?InMemoryUserDetailsManager(userDetails);
?}
??//?創(chuàng)建默認的bean?登錄客戶端,基于?授權碼、?刷新令牌的能力
?@Bean
?public?RegisteredClientRepository?registeredClientRepository()?{
??RegisteredClient?client?=?RegisteredClient.withId("pig")
????.clientId("pig")
????.clientSecret("pig")
????.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
????.authorizationGrantTypes(authorizationGrantTypes?->?{
?????authorizationGrantTypes.add(AuthorizationGrantType.AUTHORIZATION_CODE);
?????authorizationGrantTypes.add(AuthorizationGrantType.REFRESH_TOKEN);
????})
????.redirectUri("https://pig4cloud.com")
????.build();
??return?new?InMemoryRegisteredClientRepository(client);
?}
??//?指定token?生成的加解密密鑰
?@Bean
?@SneakyThrows
?public?JWKSource?jwkSource()? {
??KeyPairGenerator?keyPairGenerator?=?KeyPairGenerator.getInstance("RSA");
??keyPairGenerator.initialize(2048);
??KeyPair?keyPair?=?keyPairGenerator.generateKeyPair();
??RSAPublicKey?publicKey?=?(RSAPublicKey)?keyPair.getPublic();
??RSAPrivateKey?privateKey?=?(RSAPrivateKey)?keyPair.getPrivate();
??//?@formatter:off
??RSAKey?rsaKey=?new?RSAKey.Builder(publicKey)
????.privateKey(privateKey)
????.keyID(UUID.randomUUID().toString())
????.build();
??JWKSet?jwkSet?=?new?JWKSet(rsaKey);
??return?(jwkSelector,?securityContext)?->?jwkSelector.select(jwkSet);
?}
}
測試
授權碼認證
curl?--location?--request?GET?'http://localhost:3000/oauth2/authorize?client_id=pig&client_secret=pig&response_type=code&redirect_uri=https://pig4cloud.com'
獲取令牌
curl?--location?--request?POST?'http://localhost:3000/oauth2/token'?\
--header?'Authorization:?Basic?cGlnOnBpZw=='?\
--header?'Content-Type:?application/x-www-form-urlencoded'?\
--data-urlencode?'grant_type=authorization_code'?\
--data-urlencode?'code={code}'?\
--data-urlencode?'redirect_uri=https://pig4cloud.com'
刷新令牌
curl?--location?--request?POST?'http://localhost:3000/oauth2/token'?\
--header?'Authorization:?Basic?cGlnOnBpZw=='?\
--header?'Content-Type:?application/x-www-form-urlencoded'?\
--data-urlencode?'grant_type=refresh_token'?\
--data-urlencode?'refresh_token={refresh_token}'?\
撤銷令牌
通過 access_token
curl?--location?--request?POST?'http://localhost:3000/oauth2/revoke'?\
--header?'Authorization:?Basic?cGlnOnBpZw=='?\
--header?'Content-Type:?application/x-www-form-urlencoded'?\
--data-urlencode?'token={access_token}'?\
--data-urlencode?'token_type_hint=access_token'
通過 refresh_token
curl?--location?--request?POST?'http://localhost:3000/oauth2/revoke'?\
--header?'Authorization:?Basic?cGlnOnBpZw=='?\
--header?'Content-Type:?application/x-www-form-urlencoded'?\
--data-urlencode?'token={refresh_token}'?\
--data-urlencode?'token_type_hint=refresh_token'
內容擴展 | Token 個性化
RegisteredClient 支持個性化 token 設置的入?yún)?/section>
RegisteredClient..tokenSettings()
默認配置如下, 包括令牌有效期,刷新令牌控制等
?protected?static?Map?defaultSettings()? {
??Map?settings?=?new?HashMap<>();
??settings.put(ACCESS_TOKEN_TIME_TO_LIVE,?Duration.ofMinutes(5));
??settings.put(REUSE_REFRESH_TOKENS,?true);
??settings.put(REFRESH_TOKEN_TIME_TO_LIVE,?Duration.ofMinutes(60));
??return?settings;
?}
總結
本節(jié)源碼: https://github.com/lltx/auth-server-demo
由于官方暫時未完善相關的文檔,所有的端點入?yún)⒌刃枰獏⒖?The OAuth 2.0 Authorization Framework?
往期推薦
評論
圖片
表情
