• spring authorization server授权中心



    spring authorization server授权中心

             

    官网:https://docs.spring.io/spring-authorization-server/docs/current/reference/html/

               

                    

                                        

    授权中心

              

    spring security oauth从2.5.2 release之后不再维护,已经废弃

                       

                 

    新的授权中心由spring authorization server提供

    1. Spring Authorization Server is a framework that provides implementations
    2. of the OAuth 2.1 and OpenID Connect 1.0 specifications and other related
    3. specifications.
    4. * Spring Authorization Server实现了OAuth 2.1、OpenID Connect 1.0及其他相关规范
    5. It is built on top of Spring Security to provide a secure, light-weight,
    6. and customizable foundation for building OpenID Connect 1.0 Identity
    7. Providers and OAuth2 Authorization Server products.
    8. * Spring Authorization Server基于spring security创建,
    9. * 可用来构建安全、轻量级、个性化设置的安全认证中心

                       

    1. <dependency>
    2. <groupId>org.springframework.securitygroupId>
    3. <artifactId>spring-security-oauth2-authorization-serverartifactId>
    4. <version>0.3.1version>
    5. dependency>

               

                   

                                        

    授权模式

             

    授权码模式

                       

    1. The authorization code grant type is used to obtain both access
    2. tokens and refresh tokens and is optimized for confidential clients.
    3. Since this is a redirection-based flow, the client must be capable of
    4. interacting with the resource owner's user-agent (typically a web
    5. browser) and capable of receiving incoming requests (via redirection)
    6. from the authorization server
    7. * 授权码模式用来获取access token、refresh token,用来实现客户端加密
    8. * 授权码模式需要重定向,因此客户端需要能够与资源服务器、授权服务器进行交互
    9. The flow illustrated in Figure 3 includes the following steps:
    10. * 授权码授权流程如下:
    11. (A) The client initiates the flow by directing the resource owner's
    12. user-agent to the authorization endpoint. The client includes
    13. its client identifier, requested scope, local state, and a
    14. redirection URI to which the authorization server will send the
    15. user-agent back once access is granted (or denied).
    16. * 客户端访问资源服务器,由于没有权限,重定向到授权服务器
    17. * 客户端携带客户端标识、请求范围、local state、重定向uri
    18. (B) The authorization server authenticates the resource owner (via
    19. the user-agent) and establishes whether the resource owner
    20. grants or denies the client's access request.
    21. * 授权服务器对资源服务器进行认证,决定同意、决绝客户端的访问请求
    22. (C) Assuming the resource owner grants access, the authorization
    23. server redirects the user-agent back to the client using the
    24. redirection URI provided earlier (in the request or during
    25. client registration). The redirection URI includes an
    26. authorization code and any local state provided by the client
    27. earlier.
    28. * 如果资源服务器统一客户端的访问请求,授权服务器向客户端返回授权码
    29. (D) The client requests an access token from the authorization
    30. server's token endpoint by including the authorization code
    31. received in the previous step. When making the request, the
    32. client authenticates with the authorization server. The client
    33. includes the redirection URI used to obtain the authorization
    34. code for verification.
    35. * 客户端随后用授权码向授权服务器申请access token
    36. * 客户端的请求包含redirect uri,该uri用来验证授权码
    37. (E) The authorization server authenticates the client, validates the
    38. authorization code, and ensures that the redirection URI
    39. received matches the URI used to redirect the client in
    40. step (C). If valid, the authorization server responds back with
    41. an access token and, optionally, a refresh token
    42. * 授权服务器验证通过授权码,会向客户端返回access token
    43. * 随后客户端就可用access token,到资源服务器中访问相关权限的资源

                 

    密码模式

                       

    1. The resource owner password credentials grant type is suitable in
    2. cases where the resource owner has a trust relationship with the
    3. client, such as the device operating system or a highly privileged
    4. application. The authorization server should take special care when
    5. enabling this grant type and only allow it when other flows are not
    6. viable.
    7. * 密码模式直接通过密码获取access token,一般在可信任场景中使用
    8. * 密码模式需谨慎使用,一般在其他模式不适用时考虑使用
    9. The flow illustrated in Figure 5 includes the following steps:
    10. * 密码模式工作流程如下:
    11. (A) The resource owner provides the client with its username and
    12. password.
    13. * 客户端首先获取到用户名、密码
    14. (B) The client requests an access token from the authorization
    15. server's token endpoint by including the credentials received
    16. from the resource owner. When making the request, the client
    17. authenticates with the authorization server.
    18. * 客户端使用用户名、密码,向授权服务器申请access token
    19. (C) The authorization server authenticates the client and validates
    20. the resource owner credentials, and if valid, issues an access
    21. token.
    22. * 授权服务器验证通过后,向客户端返回access token

                   

    简化模式

                       

    1. The implicit grant type is used to obtain access tokens (it does not
    2. support the issuance of refresh tokens) and is optimized for public
    3. clients known to operate a particular redirection URI. These clients
    4. are typically implemented in a browser using a scripting language
    5. such as JavaScript
    6. * 简化模式常用语从前端直接获取access token,不保证refresh token的安全
    7. The flow illustrated in Figure 4 includes the following steps:
    8. * 简化模式工作流程如下:
    9. (A) The client initiates the flow by directing the resource owner's
    10. user-agent to the authorization endpoint. The client includes
    11. its client identifier, requested scope, local state, and a
    12. redirection URI to which the authorization server will send the
    13. user-agent back once access is granted (or denied).
    14. * 客户端访问资源服务器,请求携带携带客户端标识、访问范围、local state、重定向uri
    15. (B) The authorization server authenticates the resource owner (via
    16. the user-agent) and establishes whether the resource owner
    17. grants or denies the client's access request.
    18. * 授权服务器验证权限
    19. (C) Assuming the resource owner grants access, the authorization
    20. server redirects the user-agent back to the client using the
    21. redirection URI provided earlier. The redirection URI includes
    22. the access token in the URI fragment.
    23. * 如果资源所有者同意授权,授权服务器跳转到重定向url,跳转请求中携带access token
    24. (D) The user-agent follows the redirection instructions by making a
    25. request to the web-hosted client resource (which does not
    26. include the fragment per [RFC2616]). The user-agent retains the
    27. fragment information locally.
    28. * user-agent随后向web-hosted client resource发起请求
    29. (E) The web-hosted client resource returns a web page (typically an
    30. HTML document with an embedded script) capable of accessing the
    31. full redirection URI including the fragment retained by the
    32. user-agent, and extracting the access token (and other
    33. parameters) contained in the fragment.
    34. * web-hosted client resource返回web页面
    35. (F) The user-agent executes the script provided by the web-hosted
    36. client resource locally, which extracts the access token.
    37. * user-agent执行脚本,提取access token
    38. (G) The user-agent passes the access token to the client.
    39. * user-agent向客户端返回access token

                

    客户端模式

                       

    1. The client can request an access token using only its client
    2. credentials (or other supported means of authentication) when the
    3. client is requesting access to the protected resources under its
    4. control, or those of another resource owner that have been previously
    5. arranged with the authorization server (the method of which is beyond
    6. the scope of this specification). The client credentials grant type
    7. MUST only be used by confidential clients.
    8. * 直接使用客户端获取access token
    9. * 客户端模式必须是可信任的客户端
    10. * 客户端模式举例:postman访问权限接口获取access token
    11. The flow illustrated in Figure 6 includes the following steps:
    12. * 客户端模式工作流程如下:
    13. (A) The client authenticates with the authorization server and
    14. requests an access token from the token endpoint.
    15. * 客户端直接访问授权服务器接口,请求获取access token
    16. (B) The authorization server authenticates the client, and if valid,
    17. issues an access token.
    18. * 授权服务器认证通过,向客户端返回access token

                 

                    

                                        

    客户端注册

              

    授权中心存储客户端

    1. @Configuration
    2. public class SecurityConfig {
    3. @Bean
    4. public RegisteredClientRepository registeredClientRepository() {
    5. RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
    6. .clientId("messaging-client")
    7. .clientSecret("{noop}secret")
    8. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
    9. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
    10. .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
    11. .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
    12. .redirectUri("http://127.0.0.1:8080/login/oauth2/code/messaging-client-oidc")
    13. .redirectUri("http://127.0.0.1:8080/authorized")
    14. .scope(OidcScopes.OPENID)
    15. .scope("message.read")
    16. .scope("message.write")
    17. .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
    18. .build();
    19. return new InMemoryRegisteredClientRepository(registeredClient);
    20. } //客户端信息保存在内存中,也可保存在数据库中
    21. }

                 

    客户端配置:客户端到授权中心进行授权认证

    1. spring:
    2. security:
    3. oauth2:
    4. client:
    5. registration:
    6. client-a:
    7. provider: spring
    8. client-id: client-a
    9. client-secret: secret
    10. authorization-grant-type: authorization_code
    11. redirect-uri: "http://127.0.0.1:8080/authorized"
    12. scope: scope-a
    13. provider:
    14. spring:
    15. issuer-uri: http://localhost:9000

                         

    RegisteredClient:授权中心存储的客户端注册信息

    1. public class RegisteredClient implements Serializable {
    2. private String id; //客户端id,需唯一
    3. private String clientId; //客户端id
    4. private Instant clientIdIssuedAt; //客户端注册时间
    5. private String clientSecret; //客户端密码
    6. private Instant clientSecretExpiresAt; //客户端过期时间
    7. private String clientName; //客户端名称
    8. private Set clientAuthenticationMethods;
    9. //客户端认证方法,可选值:client_secret_basic, client_secret_post,
    10. //private_key_jwt, client_secret_jwt, and none (public clients)
    11. private Set authorizationGrantTypes;
    12. //授权类型,可选值:authorization_code, client_credentials, and refresh_token
    13. private Set redirectUris; //重定向uri
    14. private Set scopes; //授权范围
    15. private ClientSettings clientSettings; //客户端配置
    16. private TokenSettings tokenSettings; //token配置
    17. ...
    18. }

              

    RegisteredClientRepository:授权中心客户端信息存储

    1. The RegisteredClientRepository is the central component where new
    2. clients can be registered and existing clients can be queried. It
    3. is used by other components when following a specific protocol flow,
    4. such as client authentication, authorization grant processing, token
    5. introspection, dynamic client registration, and others.
    6. * RegisteredClientRepository是授权中心管理客户端信息的核心组件
    7. * 在客户端认证、授权管理、token introspection、动态注册客户端时都会使用
    8. The provided implementations of RegisteredClientRepository are
    9. InMemoryRegisteredClientRepository and JdbcRegisteredClientRepository.
    10. The InMemoryRegisteredClientRepository implementation stores
    11. RegisteredClient instances in-memory and is recommended ONLY to be
    12. used during development and testing. JdbcRegisteredClientRepository
    13. is a JDBC implementation that persists RegisteredClient instances by
    14. using JdbcOperations
    15. * InMemoryRegisteredClientRepository:客户端信息存储在授权服务器内存,一般在开发、测试时使用
    16. * JdbcRegisteredClientRepository:客户端信息存储在数据库中

              

    RegisteredClientRepository注册

    1. // 方式1:直接注册bean
    2. @Bean
    3. public RegisteredClientRepository registeredClientRepository() {
    4. List registrations = ...
    5. return new InMemoryRegisteredClientRepository(registrations);
    6. }
    7. // 方式2:OAuth2AuthorizationServerConfigurer中配置
    8. @Bean
    9. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    10. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
    11. new OAuth2AuthorizationServerConfigurer<>();
    12. http.apply(authorizationServerConfigurer);
    13. authorizationServerConfigurer
    14. .registeredClientRepository(registeredClientRepository);
    15. ...
    16. return http.build();
    17. }

             

                  

                                        

    授权token存储

             

    OAuth2Authorization:授权中心存储授权token

    1. public class OAuth2Authorization implements Serializable {
    2. private String id; //OAuth2Authorization id
    3. private String registeredClientId; //对应的client id
    4. private String principalName; //授权用户名
    5. private AuthorizationGrantType authorizationGrantType; //授权类型
    6. private Map, Token> tokens; //授权的token
    7. private Map attributes; //额外设置的属性,如:authenticated Principal,
    8. //OAuth2AuthorizationRequest, authorized scope(s)等
    9. ...
    10. }

              

    1. An OAuth2Authorization is a representation of an OAuth2 authorization,
    2. which holds state related to the authorization granted to a client,
    3. by the resource owner or itself in the case of the client_credentials
    4. authorization grant type
    5. * OAuth2Authorization用来存储客户端授权信息
    6. After the successful completion of an authorization grant flow, an
    7. OAuth2Authorization is created and associates an OAuth2AccessToken,
    8. an (optional) OAuth2RefreshToken, and additional state specific to
    9. the executed authorization grant type.
    10. * 客户端授权完成后,OAuth2Authorization用来存储生成的OAuth2AccessToken
    11. * OAuth2RefreshToken(可选)、额外的状态信息
    12. The OAuth2Token instances associated with an OAuth2Authorization vary,
    13. depending on the authorization grant type.
    14. * 授权类型不同,生成的OAuth2Token也会不同
    15. For the OAuth2 authorization_code grant, an OAuth2AuthorizationCode, an
    16. OAuth2AccessToken, and an (optional) OAuth2RefreshToken are associated.
    17. * OAuth2授权码模式,会生成OAuth2AuthorizationCode、OAuth2AccessToken、
    18. * OAuth2RefreshToken(可选)
    19. For the OpenID Connect 1.0 authorization_code grant, an
    20. OAuth2AuthorizationCode, an OidcIdToken, an OAuth2AccessToken, and
    21. an (optional) OAuth2RefreshToken are associated.
    22. * OpenID Connect 1.0授权码模式,生成OAuth2AuthorizationCode、
    23. * OidcIdToken、OAuth2AccessToken、OAuth2RefreshToken(可选)
    24. For the OAuth2 client_credentials grant, only an OAuth2AccessToken
    25. is associated
    26. * OAuth2客户端模式,只会生成OAuth2AccessToken
    27. OAuth2Authorization and its associated OAuth2Token instances have a
    28. set lifespan. A newly issued OAuth2Token is active and becomes inactive
    29. when it either expires or is invalidated (revoked). The
    30. OAuth2Authorization is (implicitly) inactive when all associated
    31. OAuth2Token instances are inactive. Each OAuth2Token is held in an
    32. OAuth2Authorization.Token, which provides accessors for isExpired(),
    33. isInvalidated(), and isActive().
    34. * OAuth2Authorization、与之关联的OAuth2Token都有生命周期
    35. * 新创建的OAuth2Token处于活跃状态,过期或者失效后处于非活跃状态
    36. * 当所有关联的OAuth2Token都不活跃时,OAuth2Authorization也会失效
    37. OAuth2Authorization.Token also provides getClaims(), which returns
    38. the claims (if any) associated with the OAuth2Token
    39. * OAuth2Authorization.Token提供了getClaims()方法,
    40. * 会返回OAuth2Token关联的claims

                 

    OAuth2AuthorizationService:OAuth2Authorization存储接口

    1. The OAuth2AuthorizationService is the central component where new authorizations are stored and existing authorizations are queried. It is used by other components when following a specific protocol flow – for example, client authentication, authorization grant processing, token introspection, token revocation, dynamic client registration, and others.
    2. * OAuth2AuthorizationService在存储、查询授权信息时使用
    3. The provided implementations of OAuth2AuthorizationService are InMemoryOAuth2AuthorizationService and JdbcOAuth2AuthorizationService. The InMemoryOAuth2AuthorizationService implementation stores OAuth2Authorization instances in-memory and is recommended ONLY to be used during development and testing. JdbcOAuth2AuthorizationService is a JDBC implementation that persists OAuth2Authorization instances by using JdbcOperations
    4. * InMemoryOAuth2AuthorizationService:授权信息存储在内存中,一般在测试、开发时使用
    5. * JdbcOAuth2AuthorizationService:授权信息存储在数据库中
    6. The OAuth2AuthorizationService is an OPTIONAL component and
    7. defaults to InMemoryOAuth2AuthorizationService
    8. * 如果不设置,默认存储在内存中

                         

    OAuth2AuthorizationService配置

    1. // 方式1:注册bean
    2. @Bean
    3. public OAuth2AuthorizationService authorizationService() {
    4. return new InMemoryOAuth2AuthorizationService();
    5. }
    6. // 方式2:OAuth2AuthorizationServerConfigurer接口配置
    7. @Bean
    8. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    9. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
    10. new OAuth2AuthorizationServerConfigurer<>();
    11. http.apply(authorizationServerConfigurer);
    12. authorizationServerConfigurer
    13. .authorizationService(authorizationService);
    14. ...
    15. return http.build();
    16. }

           

                 

                                        

    授权权限存储

           

    OAuth2AuthorizationConsent

    1. public final class OAuth2AuthorizationConsent implements Serializable {
    2. private final String registeredClientId; //对应的客户端
    3. private final String principalName; //授权用户名
    4. private final Set authorities; //授予的权限
    5. ...
    6. }

               

    1. An OAuth2AuthorizationConsent is a representation of an authorization
    2. "consent" (decision) from an OAuth2 authorization request flow – for
    3. example, the authorization_code grant, which holds the authorities
    4. granted to a client by the resource owner.
    5. * OAuth2AuthorizationConsent存储授权服务器授予客户端的权限
    6. When authorizing access to a client, the resource owner may grant only
    7. a subset of the authorities requested by the client. The typical use
    8. case is the authorization_code grant flow, in which the client requests
    9. scope(s) and the resource owner grants (or denies) access to the
    10. requested scope(s).
    11. * 认证访问权限时,资源所有者可能只会进行部分授权
    12. * 如:授权码模式,客户端设置request scope,资源所有者根据request scope决定是否授权
    13. After the completion of an OAuth2 authorization request flow, an
    14. OAuth2AuthorizationConsent is created (or updated) and associates
    15. the granted authorities with the client and resource owner
    16. * 授权结束后,会创建或者更新OAuth2AuthorizationConsent

                   

    OAuth2AuthorizationConsentService

    1. The OAuth2AuthorizationConsentService is the central component where
    2. new authorization consents are stored and existing authorization
    3. consents are queried. It is primarily used by components that implement
    4. an OAuth2 authorization request flow – for example, the
    5. authorization_code grant.
    6. * OAuth2AuthorizationConsentService用来存储客户端授予的权限信息
    7. The provided implementations of OAuth2AuthorizationConsentService
    8. are InMemoryOAuth2AuthorizationConsentService and
    9. JdbcOAuth2AuthorizationConsentService.
    10. The InMemoryOAuth2AuthorizationConsentService implementation stores
    11. OAuth2AuthorizationConsent instances in-memory and is recommended ONLY
    12. for development and testing. JdbcOAuth2AuthorizationConsentService is a
    13. JDBC implementation that persists OAuth2AuthorizationConsent instances
    14. by using JdbcOperations
    15. * InMemoryOAuth2AuthorizationConsentService:存储在内存,一般在开发、测试时使用
    16. * JdbcOAuth2AuthorizationConsentService:存储在数据库中
    17. The OAuth2AuthorizationConsentService is an OPTIONAL component
    18. and defaults to InMemoryOAuth2AuthorizationConsentService
    19. * 如果没有设置,默认存储在内存中

               

    OAuth2AuthorizationConsentService配置

    1. // 方式1:注册为bean
    2. @Bean
    3. public OAuth2AuthorizationConsentService authorizationConsentService() {
    4. return new InMemoryOAuth2AuthorizationConsentService();
    5. }
    6. // 方式2:OAuth2AuthorizationServerConfigurer注册
    7. @Bean
    8. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    9. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
    10. new OAuth2AuthorizationServerConfigurer<>();
    11. http.apply(authorizationServerConfigurer);
    12. authorizationServerConfigurer
    13. .authorizationConsentService(authorizationConsentService);
    14. ...
    15. return http.build();
    16. }

             

                        

                                        

    token 设置

           

    OAuth2TokenContext

    1. public interface OAuth2TokenContext extends Context {
    2. default RegisteredClient getRegisteredClient() ... //获取注册的客户端
    3. default <T extends Authentication> T getPrincipal() ... //获取认证用户(资源所有者)
    4. default ProviderContext getProviderContext() ... //provider上下文
    5. @Nullable
    6. default OAuth2Authorization getAuthorization() ... //获取权限授权toeken
    7. default Set<String> getAuthorizedScopes() ... //获取权限范围
    8. default OAuth2TokenType getTokenType() ... //获取token类型
    9. default AuthorizationGrantType getAuthorizationGrantType() ... //获取授权类型
    10. default <T extends Authentication> T getAuthorizationGrant() ... //获取Authentication
    11. ...
    12. }

                 

    OAuth2TokenGenerator

    1. An OAuth2TokenGenerator is responsible for generating an OAuth2Token
    2. from the information contained in the provided OAuth2TokenContext.
    3. * OAuth2TokenGenerator从OAuth2TokenContext获取信息生成OAuth2Token
    4. The OAuth2Token generated primarily depends on the type of
    5. OAuth2TokenType specified in the OAuth2TokenContext.
    6. * 根据设置的类型OAuth2TokenType生成token
    7. For example, when the value for OAuth2TokenType is:
    8. code, then OAuth2AuthorizationCode is generated.
    9. access_token, then OAuth2AccessToken is generated.
    10. refresh_token, then OAuth2RefreshToken is generated.
    11. id_token, then OidcIdToken is generated.
    12. * code:生成授权码
    13. * access_token:生成access tokn
    14. * refresh_token:生成refresh_token
    15. * id_token:生成OidcIdToken
    16. Furthermore, the format of the generated OAuth2AccessToken varies,
    17. depending on the TokenSettings.getAccessTokenFormat() configured
    18. for the RegisteredClient. If the format is OAuth2TokenFormat.SELF_CONTAINED
    19. (the default), then a Jwt is generated. If the format is
    20. OAuth2TokenFormat.REFERENCE, then an "opaque" token is generated.
    21. * TokenSettings.getAccessTokenFormat()可配置OAuth2AccessToken的格式
    22. * OAuth2TokenFormat.SELF_CONTAINED:默认,生成jwt
    23. * OAuth2TokenFormat.REFERENCE:生成opaque
    24. Finally, if the generated OAuth2Token has a set of claims and
    25. implements ClaimAccessor, the claims are made accessible from
    26. OAuth2Authorization.Token.getClaims().
    27. * 如果OAuth2Token中有claims、实现了ClaimAccessor接口
    28. * 可通过OAuth2Authorization.Token.getClaims()获取
    29. The OAuth2TokenGenerator is primarily used by components that
    30. implement authorization grant processing – for example,
    31. authorization_code, client_credentials, and refresh_token.
    32. * OAuth2TokenGenerator主要在授权时使用
    33. The provided implementations are OAuth2AccessTokenGenerator,
    34. OAuth2RefreshTokenGenerator, and JwtGenerator. The
    35. OAuth2AccessTokenGenerator generates an "opaque"
    36. (OAuth2TokenFormat.REFERENCE) access token, and the JwtGenerator
    37. generates a Jwt (OAuth2TokenFormat.SELF_CONTAINED)
    38. * 默认提供的实现类:OAuth2AccessTokenGenerator、OAuth2RefreshTokenGenerator、JwtGenerator
    39. * 格式为:OAuth2TokenFormat.REFERENCE,使用OAuth2AccessTokenGenerator生成token
    40. * 格式为:OAuth2TokenFormat.SELF_CONTAINED,使用JwtGenerator生成token
    41. The OAuth2TokenGenerator is an OPTIONAL component and defaults
    42. to a DelegatingOAuth2TokenGenerator composed of an
    43. OAuth2AccessTokenGenerator and OAuth2RefreshTokenGenerator
    44. * Auth2TokenGenerator可选,如果不设置,默认为DelegatingOAuth2TokenGenerator
    45. * DelegatingOAuth2TokenGenerator时组合生成器,包含了OAuth2AccessTokenGenerator
    46. * OAuth2RefreshTokenGenerator
    47. if a JwtEncoder @Bean or JWKSource @Bean is
    48. registered, then a JwtGenerator is additionally composed in the
    49. DelegatingOAuth2TokenGenerator
    50. * 如果注册了JwtEncoder、JWKSource实例,
    51. * JwtGenerator会自动添加到DelegatingOAuth2TokenGenerator中
    52. The OAuth2TokenGenerator provides great flexibility, as it can
    53. support any custom token format for access_token and refresh_token
    54. * OAuth2TokenGenerator支持自定义token格式

                 

    OAuth2TokenGenerator配置

    1. // 方式1:注册bean
    2. @Bean
    3. public OAuth2TokenGenerator tokenGenerator() {
    4. JwtEncoder jwtEncoder = ...
    5. JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
    6. OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
    7. OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
    8. return new DelegatingOAuth2TokenGenerator(
    9. jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    10. }
    11. //方式2:OAuth2AuthorizationServerConfigurer注册
    12. @Bean
    13. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    14. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
    15. new OAuth2AuthorizationServerConfigurer<>();
    16. http.apply(authorizationServerConfigurer);
    17. authorizationServerConfigurer
    18. .tokenGenerator(tokenGenerator);
    19. ...
    20. return http.build();
    21. }

                  

    OAuth2TokenCustomizer

    1. An OAuth2TokenCustomizer provides the ability to customize the
    2. attributes of an OAuth2Token, which are accessible in the provided OAuth2TokenContext. It is used by an OAuth2TokenGenerator to let
    3. it customize the attributes of the OAuth2Token before it is generated.
    4. * OAuth2TokenCustomizer可用来自定义OAuth2Token的attributes属性
    5. * OAuth2TokenCustomizer设置到OAuth2TokenGenerator中
    6. An OAuth2TokenCustomizer declared with a
    7. generic type of OAuth2TokenClaimsContext (implements OAuth2TokenContext)
    8. provides the ability to customize the claims of an "opaque" OAuth2AccessToken.
    9. OAuth2TokenClaimsContext.getClaims() provides access to the
    10. OAuth2TokenClaimsSet.Builder, allowing the ability to add, replace,
    11. and remove claims
    12. * OAuth2TokenCustomizer可用来设置
    13. * opaque类型的OAuth2AccessToken
    14. If the OAuth2TokenGenerator is not provided as a @Bean or is not
    15. configured through the OAuth2AuthorizationServerConfigurer, an
    16. OAuth2TokenCustomizer @Bean will automatically
    17. be configured with an OAuth2AccessTokenGenerator
    18. * 如果没有注册OAuth2TokenGenerator实例bean、使用OAuth2AuthorizationServerConfigurer注册
    19. * OAuth2TokenCustomizer会自动关联OAuth2AccessTokenGenerator
    20. An OAuth2TokenCustomizer declared with a generic type
    21. of JwtEncodingContext (implements OAuth2TokenContext) provides the ability
    22. to customize the headers and claims of a Jwt. JwtEncodingContext.getHeaders()
    23. provides access to the JwsHeader.Builder, allowing the ability to add, replace,
    24. and remove headers. JwtEncodingContext.getClaims() provides access to the
    25. JwtClaimsSet.Builder, allowing the ability to add, replace, and remove claim
    26. * OAuth2TokenCustomizer可自定义jwt的headers、claims
    27. * JwtEncodingContext.getHeaders()获取JwsHeader.Builder,可添加、替换、删除headers
    28. * JwtEncodingContext.getClaims()获取JwtClaimsSet.Builder,可添加、替换、删除claims
    29. If the OAuth2TokenGenerator is not provided as a @Bean or is not
    30. configured through the OAuth2AuthorizationServerConfigurer, an OAuth2TokenCustomizer @Bean will automatically
    31. be configured with a JwtGenerator
    32. * 如果没有注册OAuth2TokenGenerator实例bean、使用OAuth2AuthorizationServerConfigurer注册
    33. * OAuth2TokenCustomizer会自动关联JwtGenerator

                  

    opaque token自定义属性

    1. @Bean
    2. public OAuth2TokenGenerator tokenGenerator() {
    3. JwtEncoder jwtEncoder = ...
    4. JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
    5. OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
    6. accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer());
    7. //自定义的token格式
    8. OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
    9. return new DelegatingOAuth2TokenGenerator(
    10. jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    11. }
    12. @Bean
    13. public OAuth2TokenCustomizer accessTokenCustomizer() {
    14. return context -> {
    15. OAuth2TokenClaimsSet.Builder claims = context.getClaims();
    16. // Customize claims
    17. };
    18. }

           

    jwt token自定义属性

    1. @Bean
    2. public OAuth2TokenGenerator tokenGenerator() {
    3. JwtEncoder jwtEncoder = ...
    4. JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
    5. jwtGenerator.setJwtCustomizer(jwtCustomizer());
    6. OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
    7. OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
    8. return new DelegatingOAuth2TokenGenerator(
    9. jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    10. }
    11. @Bean
    12. public OAuth2TokenCustomizer jwtCustomizer() {
    13. return context -> {
    14. JwsHeader.Builder headers = context.getHeaders();
    15. JwtClaimsSet.Builder claims = context.getClaims();
    16. if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
    17. // Customize headers/claims for access_token
    18. } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
    19. // Customize headers/claims for id_token
    20. }
    21. };
    22. }

             

                   

                                        

    uri 授权路径

              

    1. ProviderSettings contains the configuration settings for the OAuth2
    2. authorization server (provider). It specifies the URI for the protocol
    3. endpoints as well as the issuer identifier
    4. * ProviderSettings设置了OAuth2授权服务器端点uri、issuer identifier配置
    5. ProviderSettings is a REQUIRED component
    6. * ProviderSettings必须设置
    7. @Import(OAuth2AuthorizationServerConfiguration.class) automatically
    8. registers a ProviderSettings @Bean, if not already provided
    9. * 如果没有设置,OAuth2AuthorizationServerConfiguration会自动导入

              

    默认 uri

    1. public final class ProviderSettings extends AbstractSettings {
    2. ...
    3. public static Builder builder() {
    4. return new Builder()
    5. .authorizationEndpoint("/oauth2/authorize")
    6. .tokenEndpoint("/oauth2/token")
    7. .tokenIntrospectionEndpoint("/oauth2/introspect")
    8. .tokenRevocationEndpoint("/oauth2/revoke")
    9. .jwkSetEndpoint("/oauth2/jwks")
    10. .oidcUserInfoEndpoint("/userinfo")
    11. .oidcClientRegistrationEndpoint("/connect/register");
    12. }
    13. ...
    14. }

          

    自定义 uri

    1. @Bean
    2. public ProviderSettings providerSettings() {
    3. return ProviderSettings.builder()
    4. .issuer("https://example.com")
    5. .authorizationEndpoint("/oauth2/v1/authorize")
    6. .tokenEndpoint("/oauth2/v1/token")
    7. .tokenIntrospectionEndpoint("/oauth2/v1/introspect")
    8. .tokenRevocationEndpoint("/oauth2/v1/revoke")
    9. .jwkSetEndpoint("/oauth2/v1/jwks")
    10. .oidcUserInfoEndpoint("/connect/v1/userinfo")
    11. .oidcClientRegistrationEndpoint("/connect/v1/register")
    12. .build();
    13. }

                 

                       

  • 相关阅读:
    tiup cluster import
    数据结构之带头双向循环链表
    口袋参谋:如何挑选淘宝热词?这一招很重要!
    【python】Python 常见文件格式 .py .pyc .pyw .pyo .pyd简介
    C++高频面试题总结
    【性能测试】Jmeter常见的命令
    shell并发遍历目录并对文件进行处理
    第5章 【MySQL】InnoDB数据页结构
    3.1_2 覆盖与交换
    新字符设备驱动示例
  • 原文地址:https://blog.csdn.net/weixin_43931625/article/details/127134961