国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring OAuth2 授權(quán)服務(wù)器配置詳解

這篇具有很好參考價(jià)值的文章主要介紹了Spring OAuth2 授權(quán)服務(wù)器配置詳解。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

配置依賴

首先要?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è)ClientIDSecret。下面是定義腳本:

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:9000issuer沒有什么問題,但是在生產(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)系。

oauth2配置資源服務(wù),spring,服務(wù)器,java,程序人生,學(xué)習(xí)文章來源地址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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • spring cloud、gradle、父子項(xiàng)目、微服務(wù)框架搭建---spring secuity oauth2、mysql 授權(quán)(九)

    spring cloud、gradle、父子項(xiàng)目、微服務(wù)框架搭建---spring secuity oauth2、mysql 授權(quán)(九)

    https://preparedata.blog.csdn.net/article/details/120062997 新建兩個(gè)服務(wù) 1.授權(quán)服務(wù) 端口號:11007 2.資源服務(wù) 端口號:11004 資源服務(wù)可以是訂單服務(wù)、用戶服務(wù)、商品服務(wù)等等 當(dāng)然這兩個(gè)服務(wù)也可以合并到一起, 依次順序AuthorizationServerConfiguration、ResourceServerConfig、WebSecurityConfiguration;

    2024年02月10日
    瀏覽(27)
  • Spring Security—OAuth2 客戶端認(rèn)證和授權(quán)

    關(guān)于 JWT Bearer 客戶端認(rèn)證的進(jìn)一步詳情,請參考OAuth 2.0客戶端認(rèn)證和授權(quán)許可的?JSON Web Token (JWT)簡介。 JWT Bearer 客戶端認(rèn)證的默認(rèn)實(shí)現(xiàn)是? NimbusJwtClientAuthenticationParametersConverter ,它是一個(gè)? Converter ,通過在? client_assertion ?參數(shù)中添加簽名的JSON Web Token(JWS)來定制令牌請求

    2024年02月08日
    瀏覽(25)
  • Spring Cloud Gateway 整合OAuth2.0 實(shí)現(xiàn)統(tǒng)一認(rèn)證授權(quán)

    Spring Cloud Gateway 整合OAuth2.0 實(shí)現(xiàn)統(tǒng)一認(rèn)證授權(quán) GateWay——向其他服務(wù)傳遞參數(shù)數(shù)據(jù) https://blog.csdn.net/qq_38322527/article/details/126530849 @EnableAuthorizationServer Oauth2ServerConfig 驗(yàn)證簽名 網(wǎng)關(guān)服務(wù)需要RSA的公鑰來驗(yàn)證簽名是否合法,所以認(rèn)證服務(wù)需要有個(gè)接口把公鑰暴露出來 接下來搭建網(wǎng)

    2024年02月13日
    瀏覽(23)
  • SpringCloud整合spring security+ oauth2+Redis實(shí)現(xiàn)認(rèn)證授權(quán)

    SpringCloud整合spring security+ oauth2+Redis實(shí)現(xiàn)認(rèn)證授權(quán)

    在微服務(wù)構(gòu)建中,我們一般用一個(gè)父工程來通知管理依賴的各種版本號信息。父工程pom文件如下: 在SpringCloud微服務(wù)體系中服務(wù)注冊中心是一個(gè)必要的存在,通過注冊中心提供服務(wù)的注冊和發(fā)現(xiàn)。具體細(xì)節(jié)可以查看我之前的博客,這里不再贅述。我們開始構(gòu)建一個(gè)eureka注冊中

    2024年02月06日
    瀏覽(25)
  • B094-人力資源項(xiàng)目-微服務(wù)授權(quán)&Oauth2

    B094-人力資源項(xiàng)目-微服務(wù)授權(quán)&Oauth2

    背景 微服務(wù)架構(gòu)下應(yīng)用散步在不同的服務(wù)器上,不是一個(gè)tomcat ,不能再基于Session 不同的服務(wù)不同的功能,都要有權(quán)限控制,不能再基于Session用Security 微服務(wù)權(quán)限控制用Redis: 微服務(wù)用Redis做權(quán)限控制數(shù)據(jù)不好存 要查Redis, 權(quán)限變動(dòng)時(shí)數(shù)據(jù)庫與redis需要同步,redis不好改,如

    2024年02月09日
    瀏覽(21)
  • oauth2-resource-server授權(quán)配置介紹

    當(dāng)了解這篇文章授權(quán)服務(wù)器后,對授權(quán)服務(wù)器有一定的認(rèn)識(shí),那么授權(quán)服務(wù)器生成token后,該怎么用呢,這就涉及到資源服務(wù)器,現(xiàn)在給大家簡單介紹實(shí)現(xiàn)過程。 2.1 基于官網(wǎng)配置 首先先配置?issuer-uri ,這里指向是授權(quán)服務(wù)器的地址 關(guān)于過濾器鏈的配置: 資源服務(wù)器將使用

    2024年02月12日
    瀏覽(25)
  • Spring Security 6.x 系列【50】授權(quán)服務(wù)器篇之Spring Boot 3.1自動(dòng)配置

    有道無術(shù),術(shù)尚可求,有術(shù)無道,止于術(shù)。 本系列Spring Boot 版本 3.10 本系列Spring Security 版本 6.1.0 本系列Spring Authorization Serve 版本 1.1.0 源碼地址:https://gitee.com/pearl-organization/study-spring-security-demo

    2024年02月08日
    瀏覽(18)
  • 電商項(xiàng)目part06 微服務(wù)網(wǎng)關(guān)整合OAuth2.0授權(quán)中心

    電商項(xiàng)目part06 微服務(wù)網(wǎng)關(guān)整合OAuth2.0授權(quán)中心

    網(wǎng)關(guān)整合 OAuth2.0 有兩種思路,一種是授權(quán)服務(wù)器生成令牌, 所有請求統(tǒng)一在網(wǎng)關(guān)層驗(yàn)證,判斷權(quán) 限等操作;另一種是由各資源服務(wù)處理,網(wǎng)關(guān)只做請求轉(zhuǎn)發(fā)。 比較常用的是第一種,把API網(wǎng)關(guān)作 為OAuth2.0的資源服務(wù)器角色,實(shí)現(xiàn)接入客戶端權(quán)限攔截、令牌解析并轉(zhuǎn)發(fā)當(dāng)前登錄

    2024年02月11日
    瀏覽(24)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授權(quán)認(rèn)證(擁抱 springboot 3.1)

    Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授權(quán)認(rèn)證(擁抱 springboot 3.1)

    目錄 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基礎(chǔ) spring security OAuth2 模塊構(gòu)成 授權(quán)方式 認(rèn)證方式 集成過程 官方demo 代碼集成 依賴 授權(quán)服務(wù)AuthorizationServerConfig配置 重要組件 測試 查看授權(quán)服務(wù)配置 訪問授權(quán)服務(wù) 授權(quán) 回調(diào) 獲取?access_token 獲取用戶信息 個(gè)性

    2024年02月08日
    瀏覽(19)
  • Spring Security OAuth2詳解

    Spring Security OAuth2詳解

    spring security oauth2框架即spring security + OAuth2,spring security上一篇文章已經(jīng)講過,接下來講講OAuth2,它是行業(yè)標(biāo)準(zhǔn)的授權(quán)協(xié)議,旨在為開發(fā)人員提供簡單易用的授權(quán)流程;OAuth 定義了四種角色: 資源所有者:能夠授予對受保護(hù)資源的訪問權(quán)限的實(shí)體,當(dāng)資源所有者是一個(gè)人時(shí),

    2024年02月03日
    瀏覽(26)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包