配置依賴
首先要?jiǎng)?chuàng)建一個(gè)Spring Boot Servlet Web項(xiàng)目,這個(gè)不難就不贅述了。集成Spring Authorization Server需要引入:
????????<!--??spring?security?starter?必須??-->
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-security</artifactId>
????????</dependency>
????????<dependency>
????????????<groupId>org.springframework.security</groupId>
????????????<artifactId>spring-security-oauth2-authorization-server</artifactId>
????????<!--??截至現(xiàn)在版本??-->
????????????<version>0.2.0</version>
????????</dependency>
OAuth2.0 Client客戶端需要注冊到授權(quán)服務(wù)器并持久化,Spring Authorization Server提供了JDBC實(shí)現(xiàn),參見JdbcRegisteredClientRepository
。為了演示方便這里我采用了H2數(shù)據(jù)庫,需要以下依賴:
????????<!--??jdbc?必須引入否則自行實(shí)現(xiàn)??-->
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-jdbc</artifactId>
????????</dependency>
????????<dependency>
????????????<groupId>com.h2database</groupId>
????????????<artifactId>h2</artifactId>
????????</dependency>
?生產(chǎn)你可以切換到其它關(guān)系型數(shù)據(jù)庫,數(shù)據(jù)庫腳本在Spring Authorization Server入門?一文的DEMO中。
Spring Authorization Server配置
接下來是Spring Authorization Server的配置。
過濾器鏈配置
根據(jù)上一文對過濾器鏈的拆解,我們需要在Spring Security的過濾器鏈中注入一些特定的過濾器。這些過濾器的配置由OAuth2AuthorizationServerConfigurer<HttpSecurity>
來完成。以下為默認(rèn)的配置:
????void?defaultOAuth2AuthorizationServerConfigurer(HttpSecurity?http)?throws?Exception?{
????????OAuth2AuthorizationServerConfigurer<HttpSecurity>?authorizationServerConfigurer?=
????????????????new?OAuth2AuthorizationServerConfigurer<>();
????????//?TODO?你可以根據(jù)需求對authorizationServerConfigurer進(jìn)行一些個(gè)性化配置
????????RequestMatcher?authorizationServerEndpointsMatcher?=?authorizationServerConfigurer.getEndpointsMatcher();
????????//?攔截?授權(quán)服務(wù)器相關(guān)的請求端點(diǎn)
????????http.requestMatcher(authorizationServerEndpointsMatcher)
????????????????.authorizeRequests().anyRequest().authenticated().and()
????????????????//?忽略掉相關(guān)端點(diǎn)的csrf
????????????????.csrf(csrf?->?csrf.ignoringRequestMatchers(authorizationServerEndpointsMatcher))
????????????????//?開啟form登錄
????????????????.formLogin()
????????????????.and()
????????????????//?應(yīng)用?授權(quán)服務(wù)器的配置
????????????????.apply(authorizationServerConfigurer);
????}
?你可以調(diào)用
OAuth2AuthorizationServerConfigurer<HttpSecurity>
提供的配置方法進(jìn)行一些個(gè)性化配置。
OAuth2.0客戶端信息持久化
這些信息會(huì)持久化到數(shù)據(jù)庫,Spring Authorization Server提供了三個(gè)DDL腳本。在入門教程的DEMO,H2會(huì)自動(dòng)初始化執(zhí)行這些DDL腳本,如果你切換到Mysql等數(shù)據(jù)庫,可能需要你自行執(zhí)行。
客戶端配置信息注冊
授權(quán)服務(wù)器要求客戶端必須是已經(jīng)注冊的,避免非法的客戶端發(fā)起授權(quán)申請。就像你平常去一些開放平臺(tái)申請一個(gè)ClientID
和Secret
。下面是定義腳本:
CREATE?TABLE?oauth2_registered_client
(
????id????????????????????????????varchar(100)????????????????????????NOT?NULL,
????client_id?????????????????????varchar(100)????????????????????????NOT?NULL,
????client_id_issued_at???????????timestamp?DEFAULT?CURRENT_TIMESTAMP?NOT?NULL,
????client_secret?????????????????varchar(200)????????????????????????NULL,
????client_secret_expires_at??????timestamp???????????????????????????NULL,
????client_name???????????????????varchar(200)????????????????????????NOT?NULL,
????client_authentication_methods?varchar(1000)???????????????????????NOT?NULL,
????authorization_grant_types?????varchar(1000)???????????????????????NOT?NULL,
????redirect_uris?????????????????varchar(1000)???????????????????????NULL,
????scopes????????????????????????varchar(1000)???????????????????????NOT?NULL,
????client_settings???????????????varchar(2000)???????????????????????NOT?NULL,
????token_settings????????????????varchar(2000)???????????????????????NOT?NULL,
????PRIMARY?KEY?(id)
);
對應(yīng)的Java類為RegisteredClient
:
public?class?RegisteredClient?implements?Serializable?{
?private?static?final?long?serialVersionUID?=?Version.SERIAL_VERSION_UID;
?private?String?id;
?private?String?clientId;
?private?Instant?clientIdIssuedAt;
?private?String?clientSecret;
?private?Instant?clientSecretExpiresAt;
?private?String?clientName;
?private?Set<ClientAuthenticationMethod>?clientAuthenticationMethods;
?private?Set<AuthorizationGrantType>?authorizationGrantTypes;
?private?Set<String>?redirectUris;
?private?Set<String>?scopes;
?private?ClientSettings?clientSettings;
?private?TokenSettings?tokenSettings;
????
????//?省略
}
定義一個(gè)客戶端可以通過下面的Builder方法實(shí)現(xiàn):
????????RegisteredClient?registeredClient?=?RegisteredClient.withId(UUID.randomUUID().toString())
//???????????????唯一的客戶端ID和密碼
????????????????.clientId("felord-client")
????????????????.clientSecret("secret")
//????????????????名稱?可不定義
????????????????.clientName("felord")
//????????????????授權(quán)方法
????????????????.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
//????????????????授權(quán)類型
????????????????.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
????????????????.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
????????????????.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
//????????????????回調(diào)地址名單,不在此列將被拒絕?而且只能使用IP或者域名??不能使用?localhost
????????????????.redirectUri("http://127.0.0.1:8080/login/oauth2/code/felord-oidc")
????????????????.redirectUri("http://127.0.0.1:8080/authorized")
????????????????.redirectUri("http://127.0.0.1:8080/foo/bar")
????????????????.redirectUri("https://baidu.com")
//????????????????OIDC支持
????????????????.scope(OidcScopes.OPENID)
//????????????????其它Scope
????????????????.scope("message.read")
????????????????.scope("message.write")
//????????????????JWT的配置項(xiàng)?包括TTL??是否復(fù)用refreshToken等等
????????????????.tokenSettings(TokenSettings.builder().build())
//????????????????配置客戶端相關(guān)的配置項(xiàng),包括驗(yàn)證密鑰或者?是否需要授權(quán)頁面
????????????????.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
????????????????.build();
持久化到數(shù)據(jù)庫的RegisteredClient
用JSON表示為:
??{
????"id":?"658cd010-4d8c-4824-a8c7-a86b642299af",
????"client_id":?"felord-client",
????"client_id_issued_at":?"2021-11-11?18:01:09",
????"client_secret":?"{bcrypt}$2a$10$XKZ8iUckDcdQWnqw682zV.DVyGuov8Sywx1KyAn4tySsw.Jtltg0.",
????"client_secret_expires_at":?null,
????"client_name":?"felord",
????"client_authentication_methods":?"client_secret_basic",
????"authorization_grant_types":?"refresh_token,client_credentials,authorization_code",
????"redirect_uris":?"http://127.0.0.1:8080/foo/bar,http://127.0.0.1:8080/authorized,http://127.0.0.1:8080/login/oauth2/code/felord-oidc,https://baidu.com",
????"scopes":?"openid,message.read,message.write",
????"client_settings":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.client.require-proof-key\":false,\"settings.client.require-authorization-consent\":true}",
????"token_settings":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.token.reuse-refresh-tokens\":true,\"settings.token.id-token-signature-algorithm\":[\"org.springframework.security.oauth2.jose.jws.SignatureAlgorithm\",\"RS256\"],\"settings.token.access-token-time-to-live\":[\"java.time.Duration\",300.000000000],\"settings.token.refresh-token-time-to-live\":[\"java.time.Duration\",3600.000000000]}"
??}
?注意上面的配置和你OAuth2.0客戶端應(yīng)用的配置息息相關(guān)。
既然持久化了,那自然需要操作該表的JDBC服務(wù)接口了,這個(gè)接口為RegisteredClientRepository
。我們需要聲明一個(gè)實(shí)現(xiàn)為Spring Bean,這里選擇基于JDBC的實(shí)現(xiàn):
???@Bean
???public?RegisteredClientRepository?registeredClientRepository(JdbcTemplate?jdbcTemplate)?{
????????return?new?JdbcRegisteredClientRepository(jdbcTemplate);
?????}
別忘記調(diào)用save(RegisteredClient)
方法把需要注冊的客戶端信息持久化。
?該實(shí)現(xiàn)依賴
spring-boot-starter-jdbc
類庫,你也可以閑得慌使用Mybatis進(jìn)行實(shí)現(xiàn)。
OAuth2授權(quán)信息持久化
記錄授權(quán)的資源擁有者(Resource Owner)對某個(gè)客戶端的某次授權(quán)記錄。對應(yīng)的Java類為OAuth2Authorization
。下面是定義腳本:
CREATE?TABLE?oauth2_authorization
(
????id????????????????????????????varchar(100)??NOT?NULL,
????registered_client_id??????????varchar(100)??NOT?NULL,
????principal_name????????????????varchar(200)??NOT?NULL,
????authorization_grant_type??????varchar(100)??NOT?NULL,
????attributes????????????????????varchar(4000)?NULL,
????state?????????????????????????varchar(500)??NULL,
????authorization_code_value??????blob??????????NULL,
????`authorization_code_issued_at`??timestamp?????NULL,
????authorization_code_expires_at?timestamp?????NULL,
????authorization_code_metadata???varchar(2000)?NULL,
????access_token_value????????????blob??????????NULL,
????access_token_issued_at????????timestamp?????NULL,
????access_token_expires_at???????timestamp?????NULL,
????access_token_metadata?????????varchar(2000)?NULL,
????access_token_type?????????????varchar(100)??NULL,
????access_token_scopes???????????varchar(1000)?NULL,
????oidc_id_token_value???????????blob??????????NULL,
????oidc_id_token_issued_at???????timestamp?????NULL,
????oidc_id_token_expires_at??????timestamp?????NULL,
????oidc_id_token_metadata????????varchar(2000)?NULL,
????refresh_token_value???????????blob??????????NULL,
????refresh_token_issued_at???????timestamp?????NULL,
????refresh_token_expires_at??????timestamp?????NULL,
????refresh_token_metadata????????varchar(2000)?NULL,
????PRIMARY?KEY?(id)
);
?這里的機(jī)制目前還沒有研究,先挖個(gè)坑。
同樣它也需要一個(gè)持久化服務(wù)接口OAuth2AuthorizationService
并注入Spring IoC:
/**
?*?管理OAuth2授權(quán)信息服務(wù)
?*
?*?@param?jdbcTemplate???????????????the?jdbc?template
?*?@param?registeredClientRepository?the?registered?client?repository
?*?@return?the?o?auth?2?authorization?service
?*/
@Bean
public?OAuth2AuthorizationService?authorizationService(JdbcTemplate?jdbcTemplate,
???????????????????????????????????????????????????????RegisteredClientRepository?registeredClientRepository)?{
????return?new?JdbcOAuth2AuthorizationService(jdbcTemplate,?
????????????registeredClientRepository);
}
持久化到數(shù)據(jù)庫的OAuth2Authorization
用JSON表示為:
??{
????"id":?"aa2f6e7d-d9b9-4360-91ef-118cbb6d4b09",
????"registered_client_id":?"658cd010-4d8c-4824-a8c7-a86b642299af",
????"principal_name":?"felord",
????"authorization_grant_type":?"authorization_code",
????"attributes":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest\":{\"@class\":\"org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest\",\"authorizationUri\":\"http://localhost:9000/oauth2/authorize\",\"authorizationGrantType\":{\"value\":\"authorization_code\"},\"responseType\":{\"value\":\"code\"},\"clientId\":\"felord-client\",\"redirectUri\":\"http://127.0.0.1:8080/foo/bar\",\"scopes\":[\"java.util.Collections$UnmodifiableSet\",[\"message.read\",\"message.write\"]],\"state\":\"9gTcVNXgV8Pn_Ron3bkFb6M92AYCodeWKoEd6xxaiUg=\",\"additionalParameters\":{\"@class\":\"java.util.Collections$UnmodifiableMap\"},\"authorizationRequestUri\":\"http://localhost:9000/oauth2/authorize?response_type=code&client_id=felord-client&scope=message.read%20message.write&state=9gTcVNXgV8Pn_Ron3bkFb6M92AYCodeWKoEd6xxaiUg%3D&redirect_uri=http://127.0.0.1:8080/foo/bar\",\"attributes\":{\"@class\":\"java.util.Collections$UnmodifiableMap\"}},\"java.security.Principal\":{\"@class\":\"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\",\"authorities\":[\"java.util.Collections$UnmodifiableRandomAccessList\",[{\"@class\":\"org.springframework.security.core.authority.SimpleGrantedAuthority\",\"authority\":\"ROLE_USER\"}]],\"details\":{\"@class\":\"org.springframework.security.web.authentication.WebAuthenticationDetails\",\"remoteAddress\":\"0:0:0:0:0:0:0:1\",\"sessionId\":\"FD624F1AD55A2418CC9815A86AA32696\"},\"authenticated\":true,\"principal\":{\"@class\":\"org.springframework.security.core.userdetails.User\",\"password\":null,\"username\":\"felord\",\"authorities\":[\"java.util.Collections$UnmodifiableSet\",[{\"@class\":\"org.springframework.security.core.authority.SimpleGrantedAuthority\",\"authority\":\"ROLE_USER\"}]],\"accountNonExpired\":true,\"accountNonLocked\":true,\"credentialsNonExpired\":true,\"enabled\":true},\"credentials\":null},\"org.springframework.security.oauth2.server.authorization.OAuth2Authorization.AUTHORIZED_SCOPE\":[\"java.util.Collections$UnmodifiableSet\",[\"message.read\",\"message.write\"]]}",
????"state":?null,
????"authorization_code_value":?"EZFxDcsKoaGtyqRTS0oNMg85EcVcyLdVssuD3SV-o0FvNXsSTRjTmCdu0ZPZnVIQ7K4TTSzrvLwBqoRXOigo_dWVNeqE44LjHHL_KtujM_Mxz8hLZgGhtfipvTdpWWR1",
????"authorization_code_issued_at":?"2021-11-11?18:44:45",
????"authorization_code_expires_at":?"2021-11-11?18:49:45",
????"authorization_code_metadata":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"metadata.token.invalidated\":true}",
????"access_token_value":?"eyJ4NXQjUzI1NiI6IlZGR1F4Q21nSEloX2dhRi13UGIxeEM5b0tBMXc1bGEwRUZtcXFQTXJxbXciLCJraWQiOiJmZWxvcmRjbiIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJmZWxvcmQiLCJhdWQiOiJmZWxvcmQtY2xpZW50IiwibmJmIjoxNjM2NjI3NDg0LCJzY29wZSI6WyJtZXNzYWdlLnJlYWQiLCJtZXNzYWdlLndyaXRlIl0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo5MDAwIiwiZXhwIjoxNjM2NjI3Nzg0LCJpYXQiOjE2MzY2Mjc0ODR9.CFzye9oIh8-ZMpyp9XoIXIQLnj2Sn17yZ9bgn7NYAbrp2hRq-Io_Se2SJpSEMa_Ce44aOGmcLTmIOILYUxlU08QCtHgr4UfCZttzroQhEn3Qui7fixBMprPYqxmu2KL5G_l3q5EWyh4G0ilHpByCBDeBGAl7FpaxSDlelnBfNGs9q6nJCs7aC40U_YPBRLoCBLVK1Y8t8kQvNu8NqCkS5D5DZAogpmlVg7jSIPz1UXVIh7iDTTQ1wJl6rZ1E87E0UroX4eSuYfMQ351y65IUlB14hvKhu03yDLTiVKtujOo3m0DAkJTbk3ZkFZEmDf4N3Yn-ktU7cyswQWa1bKf3og",
????"access_token_issued_at":?"2021-11-11?18:44:45",
????"access_token_expires_at":?"2021-11-11?18:49:45",
????"access_token_metadata":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"metadata.token.claims\":{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"sub\":\"felord\",\"aud\":[\"java.util.Collections$SingletonList\",[\"felord-client\"]],\"nbf\":[\"java.time.Instant\",1636627484.674000000],\"scope\":[\"java.util.Collections$UnmodifiableSet\",[\"message.read\",\"message.write\"]],\"iss\":[\"java.net.URL\",\"http://localhost:9000\"],\"exp\":[\"java.time.Instant\",1636627784.674000000],\"iat\":[\"java.time.Instant\",1636627484.674000000]},\"metadata.token.invalidated\":false}",
????"access_token_type":?"Bearer",
????"access_token_scopes":?"message.read,message.write",
????"oidc_id_token_value":?null,
????"oidc_id_token_issued_at":?null,
????"oidc_id_token_expires_at":?null,
????"oidc_id_token_metadata":?null,
????"refresh_token_value":?"hbD9dVMpu855FhDDOYapwsQSx8zO9iPX5LUZKeXWzUcbE2rgYRV-sgXl5vGwyByLNljcqVyK9Pgquzbcoe6dkt0_yPQPJfxLY8ezEQ-QREBjxNYqecd6OI9SHMQkBObG",
????"refresh_token_issued_at":?"2021-11-11?18:44:45",
????"refresh_token_expires_at":?"2021-11-11?19:44:45",
????"refresh_token_metadata":?"{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"metadata.token.invalidated\":false}"
??}
?存儲(chǔ)的東西還是比較全的,甚至把Java類都序列化了。
確認(rèn)授權(quán)持久化
資源擁有者(Resource Owner)對授權(quán)的確認(rèn)信息OAuth2AuthorizationConsent
的持久化,這個(gè)比較簡單。下面是定義腳本:
CREATE?TABLE?oauth2_authorization_consent
(
????registered_client_id?varchar(100)??NOT?NULL,
????principal_name???????varchar(200)??NOT?NULL,
????authorities??????????varchar(1000)?NOT?NULL,
????PRIMARY?KEY?(registered_client_id,?principal_name)
);
對應(yīng)的持久化服務(wù)接口為OAuth2AuthorizationConsentService
,也要注入Spring IoC:
@Bean
public?OAuth2AuthorizationConsentService?authorizationConsentService(JdbcTemplate?jdbcTemplate,?
?????????????????????????????????????????????????????????????????????RegisteredClientRepository?registeredClientRepository)?{
????return?new?JdbcOAuth2AuthorizationConsentService(jdbcTemplate,?registeredClientRepository);
}
持久化到數(shù)據(jù)庫的OAuth2AuthorizationConsent
用JSON表示為:
??{
????"registered_client_id":?"658cd010-4d8c-4824-a8c7-a86b642299af",
????"principal_name":?"felord",
????"authorities":?"SCOPE_message.read,SCOPE_message.write"
??}
JWK
JWK全稱JSON Web Key,是一個(gè)將加密的密鑰用JSON對象描述的規(guī)范,和JWT一樣是JOSE規(guī)范的重要組成部分。規(guī)范的詳細(xì)定義可參考JWK文檔。JWK參考示例:
{
????"keys":?[
????????{
????????????"kty":?"RSA",
????????????"x5t#S256":?"VFGQxCmgHIh_gaF-wPb1xC9oKA1w5la0EFmqqPMrqmw",
????????????"e":?"AQAB",
????????????"kid":?"felordcn",
????????????"x5c":?[
"MIIDczCCAlugAwIBAgIEURwmYzANBgkqhkiG9w0BAQsFADBqMQ0wCwYDVQQGEwQoY24pMQ0wCwYDVQQIEwQoaG4pMQ0wCwYDVQQHEwQoenopMRMwEQYDVQQKEwooZmVsb3JkY24pMRMwEQYDVQQLEwooZmVsb3JkY24pMREwDwYDVQQDEwgoRmVsb3JkKTAeFw0yMTEwMTgwNDUwMTRaFw0yMjEwMTgwNDUwMTRaMGoxDTALBgNVBAYTBChjbikxDTALBgNVBAgTBChobikxDTALBgNVBAcTBCh6eikxEzARBgNVBAoTCihmZWxvcmRjbikxEzARBgNVBAsTCihmZWxvcmRjbikxETAPBgNVBAMTCChGZWxvcmQpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgo0TPk1td7iROmmLcGbOsZ2F68kTertDwRyk+leqBl+qyJAkjoVgVaCRRQHZmvu/YGp93vOaEd/zFdVj/rFvMXmwBxgYPOeSG0bHkYtFBaUiLf1vhW5lyiPHcGide3uw1p+il3JNiOpcnLCbAKZgzm4qaugeuOD02/M0YcMW2Jqg3SUWpC+9vu9yt5dVc1xpmpwEAamKzvynI3Zxl44ddlA8RRAS6kV0OUcKbEG63G3yZ4MHnhrFrZDuvlwfSSgn0wFOC/b6mJ+bUxByMAXKD0d4DS2B2mVl7RO5AzL4SFcqtZZE3Drtcli67bsENyOQeoTVaKO6gu5PEEFlQ7pHKwIDAQABoyEwHzAdBgNVHQ4EFgQUqbLZ76DtdEEpTZUcgP7LsdGk8/AwDQYJKoZIhvcNAQELBQADggEBAEzfhi6/B00NxSPKAYJea/0MIyHr4X8Ue6Du+xl2q0UFzSkyIiMcPNmOYW5L1PWGjxR5IIiUgxKI5bEvhLkHhkMV+GRQSPKJXeC3szHdoZ3fXDZnuC0I88a1YDsvzuVhyjLL/n5lETRT4QWo5LsAj5v7AX+p46HM0iqSyTptafm2wheEosFA3ro4+vEDRaMrKLY1KdJuvvrrQIRpplhB/JbncmjWrEEvICSLEXm+kdGFgWNXkNxF0PhTLyPu3tEb2xLmjFltALwi3KPUGv9zVjxb7KyYiMnVsOPnwpDLOyREM9j4RLDiwf0tsCqPqltVExvFZouoL26fhcozfcrqC70="
????????????],
????????????"n":?"go0TPk1td7iROmmLcGbOsZ2F68kTertDwRyk-leqBl-qyJAkjoVgVaCRRQHZmvu_YGp93vOaEd_zFdVj_rFvMXmwBxgYPOeSG0bHkYtFBaUiLf1vhW5lyiPHcGide3uw1p-il3JNiOpcnLCbAKZgzm4qaugeuOD02_M0YcMW2Jqg3SUWpC-9vu9yt5dVc1xpmpwEAamKzvynI3Zxl44ddlA8RRAS6kV0OUcKbEG63G3yZ4MHnhrFrZDuvlwfSSgn0wFOC_b6mJ-bUxByMAXKD0d4DS2B2mVl7RO5AzL4SFcqtZZE3Drtcli67bsENyOQeoTVaKO6gu5PEEFlQ7pHKw"
????????}
????]
}
?JWK的意義在于生成JWT和提供JWK端點(diǎn)給OAuth2.0資源服務(wù)器解碼校驗(yàn)JWT。
公私鑰
JWK會(huì)涉及到加密算法,這里使用RSASHA256
算法來作為加密算法,并通過Keytool工具來生成.jks
公私鑰證書文件。當(dāng)然你也可以通過openssl來生成pkcs12格式的證書。在Spring Security實(shí)戰(zhàn)干貨中已經(jīng)對生成的方法進(jìn)行了說明,這里不再贅述。
JWKSource
由于Spring Security的JOSE實(shí)現(xiàn)依賴的是nimbus-jose-jwt
,所以這里只需要我們實(shí)現(xiàn)JWKSource <C extends SecurityContext>
并注入Spring IoC即可。相關(guān)代碼如下:
????/**
?????*?加載JWK資源
?????*
?????*?@return?the?jwk?source
?????*/
????@SneakyThrows
????@Bean
????public?JWKSource<SecurityContext>?jwkSource()?{
????????//TODO?這里優(yōu)化到配置
????????//?證書的路徑
????????String?path?=?"felordcn.jks";
????????//?證書別名
????????String?alias?=?"felordcn";
????????//?keystore?密碼
????????String?pass?=?"123456";
????????ClassPathResource?resource?=?new?ClassPathResource(path);
????????KeyStore?jks?=?KeyStore.getInstance("jks");
//????????KeyStore?pkcs12?=?KeyStore.getInstance("pkcs12");
????????char[]?pin?=?pass.toCharArray();
????????jks.load(resource.getInputStream(),?pin);
????????RSAKey?rsaKey?=?RSAKey.load(jks,?alias,?pin);
????????JWKSet?jwkSet?=?new?JWKSet(rsaKey);
????????return?(jwkSelector,?securityContext)?->?jwkSelector.select(jwkSet);
????}
授權(quán)服務(wù)器元信息配置
客戶端信息RegisteredClient
包含了Token的配置項(xiàng)TokenSettings
和客戶端配置項(xiàng)ClientSettings
。授權(quán)服務(wù)器本身也提供了一個(gè)配置工具來配置其元信息,大多數(shù)我們都使用默認(rèn)配置即可,唯一需要配置的其實(shí)只有授權(quán)服務(wù)器的地址issuer
,在DEMO中雖然我使用localhost:9000
了issuer
沒有什么問題,但是在生產(chǎn)中這個(gè)地方應(yīng)該配置為域名。
????/**
?????*?配置?OAuth2.0?provider元信息
?????*
?????*?@return?the?provider?settings
?????*/
????@Bean
????public?ProviderSettings?providerSettings(@Value("${server.port}")?Integer?port)?{
????????//TODO?生產(chǎn)應(yīng)該使用域名
????????return?ProviderSettings.builder().issuer("http://localhost:"?+?port).build();
????}
?你可以修改本地的hosts文件試試用域名。
到這里Spring Authorization Server的配置就完成了,但是整個(gè)授權(quán)服務(wù)器的配置還沒有完成。
授權(quán)服務(wù)器安全配置
上面是授權(quán)服務(wù)器本身的配置,授權(quán)服務(wù)器本身的安全配置是另外一條過濾器鏈承擔(dān)的,我們也要對它進(jìn)行一些配置,都是常規(guī)的Spring Security配置,這里給一個(gè)簡單的配置,也是DEMO中的配置:
@EnableWebSecurity(debug?=?true)
public?class?DefaultSecurityConfig?{
????//?@formatter:off
????@Bean
????SecurityFilterChain?defaultSecurityFilterChain(HttpSecurity?http)?throws?Exception?{
????????http.authorizeRequests(authorizeRequests?->
????????????????????????authorizeRequests.anyRequest().authenticated()
????????????????)
????????????????.formLogin();
????????return?http.build();
????}
????//?@formatter:on
????/**
?????*?在內(nèi)存中抽象一個(gè)Spring?Security安全用戶{@link?User},同時(shí)該用戶也是Resource?Owner;
?????*?實(shí)際開發(fā)中需要持久化到數(shù)據(jù)庫。
?????*
?????*?@return?the?user?details?service
?????*/
//?@formatter:off
????@Bean
????UserDetailsService?users()?{
????????UserDetails?user?=?User.builder()
????????????????.username("felord")
????????????????.password("password")
????????????????.passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
????????????????.roles("USER")
????????????????.build();
????????return?new?InMemoryUserDetailsManager(user);
????}
????//?@formatter:on
????/**
?????*?開放一些端點(diǎn)的訪問控制。
?????*
?????*?如果你使用了一些依賴這些端點(diǎn)的程序,比如Consul健康檢查;
?????*?打開H2數(shù)據(jù)庫web控制臺(tái)訪問控制,方便你查看數(shù)據(jù)具體看配置文件說明。
?????*
?????*?@return?the?web?security?customizer
?????*/
????@Bean
????WebSecurityCustomizer?webSecurityCustomizer()?{
????????return?web?->?web.ignoring().antMatchers("/actuator/health","/h2-console/**");
????}
}
到這里一個(gè)基于Spring Authorization Server的授權(quán)服務(wù)器就搭建好了。
解惑
?為什么一個(gè)項(xiàng)目配置了兩個(gè)甚至多個(gè)
SecurityFilterChain
?
之所以有兩個(gè)SecurityFilterChain
是因?yàn)槌绦蛟O(shè)計(jì)要保證職責(zé)單一,無論是底層架構(gòu)還是業(yè)務(wù)代碼,為此HttpSecurity
被以基于原型(prototype)的Spring Bean注入Spring IoC。針對本應(yīng)用中的兩條過濾器鏈,分別是授權(quán)服務(wù)器的過濾器鏈和應(yīng)用安全的過濾器鏈,它們之間其實(shí)互相沒有太多聯(lián)系。文章來源:http://www.zghlxwxcb.cn/news/detail-850288.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-850288.html
到了這里,關(guān)于Spring OAuth2 授權(quán)服務(wù)器配置詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!