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提供

Spring Authorization Server is a framework that provides implementations 
of the OAuth 2.1 and OpenID Connect 1.0 specifications and other related 
specifications. 
* Spring Authorization Server实现了OAuth 2.1、OpenID Connect 1.0及其他相关规范

It is built on top of Spring Security to provide a secure, light-weight, 
and customizable foundation for building OpenID Connect 1.0 Identity 
Providers and OAuth2 Authorization Server products.
* Spring Authorization Server基于spring security创建,
* 可用来构建安全、轻量级、个性化设置的安全认证中心

                   

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>0.3.1</version>
</dependency>

           

               

                                    

授权模式

         

授权码模式

                   

The authorization code grant type is used to obtain both access
tokens and refresh tokens and is optimized for confidential clients.
Since this is a redirection-based flow, the client must be capable of
interacting with the resource owner's user-agent (typically a web
browser) and capable of receiving incoming requests (via redirection)
from the authorization server
* 授权码模式用来获取access token、refresh token,用来实现客户端加密
* 授权码模式需要重定向,因此客户端需要能够与资源服务器、授权服务器进行交互


The flow illustrated in Figure 3 includes the following steps:
* 授权码授权流程如下:

   (A)  The client initiates the flow by directing the resource owner's
        user-agent to the authorization endpoint.  The client includes
        its client identifier, requested scope, local state, and a
        redirection URI to which the authorization server will send the
        user-agent back once access is granted (or denied).
        * 客户端访问资源服务器,由于没有权限,重定向到授权服务器
        * 客户端携带客户端标识、请求范围、local state、重定向uri

   (B)  The authorization server authenticates the resource owner (via
        the user-agent) and establishes whether the resource owner
        grants or denies the client's access request.
        * 授权服务器对资源服务器进行认证,决定同意、决绝客户端的访问请求

   (C)  Assuming the resource owner grants access, the authorization
        server redirects the user-agent back to the client using the
        redirection URI provided earlier (in the request or during
        client registration).  The redirection URI includes an
        authorization code and any local state provided by the client
        earlier.
        * 如果资源服务器统一客户端的访问请求,授权服务器向客户端返回授权码

   (D)  The client requests an access token from the authorization
        server's token endpoint by including the authorization code
        received in the previous step.  When making the request, the
        client authenticates with the authorization server.  The client
        includes the redirection URI used to obtain the authorization
        code for verification.
        * 客户端随后用授权码向授权服务器申请access token
        * 客户端的请求包含redirect uri,该uri用来验证授权码

   (E)  The authorization server authenticates the client, validates the
        authorization code, and ensures that the redirection URI
        received matches the URI used to redirect the client in
        step (C).  If valid, the authorization server responds back with
        an access token and, optionally, a refresh token
        * 授权服务器验证通过授权码,会向客户端返回access token
        * 随后客户端就可用access token,到资源服务器中访问相关权限的资源

             

密码模式

                   

The resource owner password credentials grant type is suitable in
cases where the resource owner has a trust relationship with the
client, such as the device operating system or a highly privileged
application.  The authorization server should take special care when
enabling this grant type and only allow it when other flows are not
viable.
* 密码模式直接通过密码获取access token,一般在可信任场景中使用
* 密码模式需谨慎使用,一般在其他模式不适用时考虑使用


The flow illustrated in Figure 5 includes the following steps:
* 密码模式工作流程如下:

   (A)  The resource owner provides the client with its username and
        password.
        * 客户端首先获取到用户名、密码

   (B)  The client requests an access token from the authorization
        server's token endpoint by including the credentials received
        from the resource owner.  When making the request, the client
        authenticates with the authorization server.
        * 客户端使用用户名、密码,向授权服务器申请access token

   (C)  The authorization server authenticates the client and validates
        the resource owner credentials, and if valid, issues an access
        token.
        * 授权服务器验证通过后,向客户端返回access token

               

简化模式

                   

The implicit grant type is used to obtain access tokens (it does not
support the issuance of refresh tokens) and is optimized for public
clients known to operate a particular redirection URI.  These clients
are typically implemented in a browser using a scripting language
such as JavaScript
* 简化模式常用语从前端直接获取access token,不保证refresh token的安全


The flow illustrated in Figure 4 includes the following steps:
* 简化模式工作流程如下:

   (A)  The client initiates the flow by directing the resource owner's
        user-agent to the authorization endpoint.  The client includes
        its client identifier, requested scope, local state, and a
        redirection URI to which the authorization server will send the
        user-agent back once access is granted (or denied).
        * 客户端访问资源服务器,请求携带携带客户端标识、访问范围、local state、重定向uri

   (B)  The authorization server authenticates the resource owner (via
        the user-agent) and establishes whether the resource owner
        grants or denies the client's access request.
        * 授权服务器验证权限

   (C)  Assuming the resource owner grants access, the authorization
        server redirects the user-agent back to the client using the
        redirection URI provided earlier.  The redirection URI includes
        the access token in the URI fragment.
        * 如果资源所有者同意授权,授权服务器跳转到重定向url,跳转请求中携带access token

   (D)  The user-agent follows the redirection instructions by making a
        request to the web-hosted client resource (which does not
        include the fragment per [RFC2616]).  The user-agent retains the
        fragment information locally.
        * user-agent随后向web-hosted client resource发起请求

   (E)  The web-hosted client resource returns a web page (typically an
        HTML document with an embedded script) capable of accessing the
        full redirection URI including the fragment retained by the
        user-agent, and extracting the access token (and other
        parameters) contained in the fragment.
        * web-hosted client resource返回web页面

   (F)  The user-agent executes the script provided by the web-hosted
        client resource locally, which extracts the access token.
        * user-agent执行脚本,提取access token
        
   (G)  The user-agent passes the access token to the client.
        * user-agent向客户端返回access token

            

客户端模式

                   

The client can request an access token using only its client
credentials (or other supported means of authentication) when the
client is requesting access to the protected resources under its
control, or those of another resource owner that have been previously
arranged with the authorization server (the method of which is beyond
the scope of this specification). The client credentials grant type 
MUST only be used by confidential clients.
* 直接使用客户端获取access token
* 客户端模式必须是可信任的客户端
* 客户端模式举例:postman访问权限接口获取access token


The flow illustrated in Figure 6 includes the following steps:
* 客户端模式工作流程如下:

   (A)  The client authenticates with the authorization server and
        requests an access token from the token endpoint.
        * 客户端直接访问授权服务器接口,请求获取access token

   (B)  The authorization server authenticates the client, and if valid,
        issues an access token.
        * 授权服务器认证通过,向客户端返回access token

             

                

                                    

客户端注册

          

授权中心存储客户端

@Configuration
public class SecurityConfig {

	@Bean 
	public RegisteredClientRepository registeredClientRepository() {
		RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
				.clientId("messaging-client")
				.clientSecret("{noop}secret")
				.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
				.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
				.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
				.redirectUri("http://127.0.0.1:8080/login/oauth2/code/messaging-client-oidc")
				.redirectUri("http://127.0.0.1:8080/authorized")
				.scope(OidcScopes.OPENID)
				.scope("message.read")
				.scope("message.write")
				.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
				.build();

		return new InMemoryRegisteredClientRepository(registeredClient);
	}          //客户端信息保存在内存中,也可保存在数据库中

}

             

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

spring:
  security:
    oauth2:
      client:
        registration:
          client-a:
            provider: spring
            client-id: client-a
            client-secret: secret
            authorization-grant-type: authorization_code
            redirect-uri: "http://127.0.0.1:8080/authorized"
            scope: scope-a
        provider:
          spring:
            issuer-uri: http://localhost:9000

                     

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

public class RegisteredClient implements Serializable {
	private String id;                  //客户端id,需唯一
	private String clientId;            //客户端id
	private Instant clientIdIssuedAt;   //客户端注册时间
	private String clientSecret;        //客户端密码
	private Instant clientSecretExpiresAt;  //客户端过期时间
	private String clientName;              //客户端名称
	private Set<ClientAuthenticationMethod> clientAuthenticationMethods;
                   //客户端认证方法,可选值:client_secret_basic, client_secret_post, 
                   //private_key_jwt, client_secret_jwt, and none (public clients)
	private Set<AuthorizationGrantType> authorizationGrantTypes;
                                        //授权类型,可选值:authorization_code, client_credentials, and refresh_token
	private Set<String> redirectUris;       //重定向uri
	private Set<String> scopes;             //授权范围
	private ClientSettings clientSettings;  //客户端配置
	private TokenSettings tokenSettings;    //token配置

	...

}

          

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

The RegisteredClientRepository is the central component where new 
clients can be registered and existing clients can be queried. It 
is used by other components when following a specific protocol flow, 
such as client authentication, authorization grant processing, token 
introspection, dynamic client registration, and others.
* RegisteredClientRepository是授权中心管理客户端信息的核心组件
* 在客户端认证、授权管理、token introspection、动态注册客户端时都会使用

The provided implementations of RegisteredClientRepository are 
InMemoryRegisteredClientRepository and JdbcRegisteredClientRepository. 
The InMemoryRegisteredClientRepository implementation stores 
RegisteredClient instances in-memory and is recommended ONLY to be 
used during development and testing. JdbcRegisteredClientRepository 
is a JDBC implementation that persists RegisteredClient instances by 
using JdbcOperations
* InMemoryRegisteredClientRepository:客户端信息存储在授权服务器内存,一般在开发、测试时使用
* JdbcRegisteredClientRepository:客户端信息存储在数据库中

          

RegisteredClientRepository注册

// 方式1:直接注册bean
@Bean
public RegisteredClientRepository registeredClientRepository() {
	List<RegisteredClient> registrations = ...
	return new InMemoryRegisteredClientRepository(registrations);
}


// 方式2:OAuth2AuthorizationServerConfigurer中配置
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
		.registeredClientRepository(registeredClientRepository);

	...

	return http.build();
}


         

              

                                    

授权token存储

         

OAuth2Authorization:授权中心存储授权token

public class OAuth2Authorization implements Serializable {
	private String id;                     //OAuth2Authorization id
	private String registeredClientId;     //对应的client id
	private String principalName;          //授权用户名
	private AuthorizationGrantType authorizationGrantType;        //授权类型
	private Map<Class<? extends OAuth2Token>, Token<?>> tokens;   //授权的token
	private Map<String, Object> attributes; //额外设置的属性,如:authenticated Principal, 
                                            //OAuth2AuthorizationRequest, authorized scope(s)等

	...

}

          

An OAuth2Authorization is a representation of an OAuth2 authorization, 
which holds state related to the authorization granted to a client, 
by the resource owner or itself in the case of the client_credentials 
authorization grant type
* OAuth2Authorization用来存储客户端授权信息

After the successful completion of an authorization grant flow, an 
OAuth2Authorization is created and associates an OAuth2AccessToken, 
an (optional) OAuth2RefreshToken, and additional state specific to 
the executed authorization grant type.
* 客户端授权完成后,OAuth2Authorization用来存储生成的OAuth2AccessToken
* OAuth2RefreshToken(可选)、额外的状态信息

The OAuth2Token instances associated with an OAuth2Authorization vary, 
depending on the authorization grant type.
* 授权类型不同,生成的OAuth2Token也会不同

For the OAuth2 authorization_code grant, an OAuth2AuthorizationCode, an 
OAuth2AccessToken, and an (optional) OAuth2RefreshToken are associated.
* OAuth2授权码模式,会生成OAuth2AuthorizationCode、OAuth2AccessToken、
* OAuth2RefreshToken(可选)

For the OpenID Connect 1.0 authorization_code grant, an 
OAuth2AuthorizationCode, an OidcIdToken, an OAuth2AccessToken, and 
an (optional) OAuth2RefreshToken are associated.
* OpenID Connect 1.0授权码模式,生成OAuth2AuthorizationCode、
* OidcIdToken、OAuth2AccessToken、OAuth2RefreshToken(可选)

For the OAuth2 client_credentials grant, only an OAuth2AccessToken 
is associated
* OAuth2客户端模式,只会生成OAuth2AccessToken


OAuth2Authorization and its associated OAuth2Token instances have a 
set lifespan. A newly issued OAuth2Token is active and becomes inactive 
when it either expires or is invalidated (revoked). The 
OAuth2Authorization is (implicitly) inactive when all associated 
OAuth2Token instances are inactive. Each OAuth2Token is held in an 
OAuth2Authorization.Token, which provides accessors for isExpired(), 
isInvalidated(), and isActive().
* OAuth2Authorization、与之关联的OAuth2Token都有生命周期
* 新创建的OAuth2Token处于活跃状态,过期或者失效后处于非活跃状态
* 当所有关联的OAuth2Token都不活跃时,OAuth2Authorization也会失效

OAuth2Authorization.Token also provides getClaims(), which returns 
the claims (if any) associated with the OAuth2Token
* OAuth2Authorization.Token提供了getClaims()方法,
* 会返回OAuth2Token关联的claims

             

OAuth2AuthorizationService:OAuth2Authorization存储接口

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.
* OAuth2AuthorizationService在存储、查询授权信息时使用

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
* InMemoryOAuth2AuthorizationService:授权信息存储在内存中,一般在测试、开发时使用
* JdbcOAuth2AuthorizationService:授权信息存储在数据库中

The OAuth2AuthorizationService is an OPTIONAL component and 
defaults to InMemoryOAuth2AuthorizationService
* 如果不设置,默认存储在内存中

                     

OAuth2AuthorizationService配置

// 方式1:注册bean
@Bean
public OAuth2AuthorizationService authorizationService() {
	return new InMemoryOAuth2AuthorizationService();
}

// 方式2:OAuth2AuthorizationServerConfigurer接口配置
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
		.authorizationService(authorizationService);

	...

	return http.build();
}

       

             

                                    

授权权限存储

       

OAuth2AuthorizationConsent

public final class OAuth2AuthorizationConsent implements Serializable {
	private final String registeredClientId;          //对应的客户端
	private final String principalName;               //授权用户名
	private final Set<GrantedAuthority> authorities;  //授予的权限

	...

}

           

An OAuth2AuthorizationConsent is a representation of an authorization 
"consent" (decision) from an OAuth2 authorization request flow – for 
example, the authorization_code grant, which holds the authorities 
granted to a client by the resource owner.
* OAuth2AuthorizationConsent存储授权服务器授予客户端的权限

When authorizing access to a client, the resource owner may grant only 
a subset of the authorities requested by the client. The typical use 
case is the authorization_code grant flow, in which the client requests 
scope(s) and the resource owner grants (or denies) access to the 
requested scope(s).
* 认证访问权限时,资源所有者可能只会进行部分授权
* 如:授权码模式,客户端设置request scope,资源所有者根据request scope决定是否授权

After the completion of an OAuth2 authorization request flow, an 
OAuth2AuthorizationConsent is created (or updated) and associates 
the granted authorities with the client and resource owner
* 授权结束后,会创建或者更新OAuth2AuthorizationConsent

               

OAuth2AuthorizationConsentService

The OAuth2AuthorizationConsentService is the central component where 
new authorization consents are stored and existing authorization 
consents are queried. It is primarily used by components that implement 
an OAuth2 authorization request flow – for example, the 
authorization_code grant.
* OAuth2AuthorizationConsentService用来存储客户端授予的权限信息

The provided implementations of OAuth2AuthorizationConsentService 
are InMemoryOAuth2AuthorizationConsentService and
JdbcOAuth2AuthorizationConsentService. 
The InMemoryOAuth2AuthorizationConsentService implementation stores 
OAuth2AuthorizationConsent instances in-memory and is recommended ONLY 
for development and testing. JdbcOAuth2AuthorizationConsentService is a 
JDBC implementation that persists OAuth2AuthorizationConsent instances 
by using JdbcOperations
* InMemoryOAuth2AuthorizationConsentService:存储在内存,一般在开发、测试时使用
* JdbcOAuth2AuthorizationConsentService:存储在数据库中

The OAuth2AuthorizationConsentService is an OPTIONAL component 
and defaults to InMemoryOAuth2AuthorizationConsentService
* 如果没有设置,默认存储在内存中

           

OAuth2AuthorizationConsentService配置

// 方式1:注册为bean
@Bean
public OAuth2AuthorizationConsentService authorizationConsentService() {
	return new InMemoryOAuth2AuthorizationConsentService();
}


// 方式2:OAuth2AuthorizationServerConfigurer注册
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
		.authorizationConsentService(authorizationConsentService);

	...

	return http.build();
}

         

                    

                                    

token 设置

       

OAuth2TokenContext

public interface OAuth2TokenContext extends Context {

	default RegisteredClient getRegisteredClient() ...       //获取注册的客户端

	default <T extends Authentication> T getPrincipal() ...  //获取认证用户(资源所有者)
	default ProviderContext getProviderContext() ...    //provider上下文
	@Nullable
	default OAuth2Authorization getAuthorization() ...  //获取权限授权toeken

	default Set<String> getAuthorizedScopes() ...       //获取权限范围

	default OAuth2TokenType getTokenType() ...          //获取token类型

	default AuthorizationGrantType getAuthorizationGrantType() ...   //获取授权类型

	default <T extends Authentication> T getAuthorizationGrant() ... //获取Authentication

	...

}

             

OAuth2TokenGenerator

An OAuth2TokenGenerator is responsible for generating an OAuth2Token 
from the information contained in the provided OAuth2TokenContext.
* OAuth2TokenGenerator从OAuth2TokenContext获取信息生成OAuth2Token

The OAuth2Token generated primarily depends on the type of 
OAuth2TokenType specified in the OAuth2TokenContext.
* 根据设置的类型OAuth2TokenType生成token

For example, when the value for OAuth2TokenType is:
    code, then OAuth2AuthorizationCode is generated.
    access_token, then OAuth2AccessToken is generated.
    refresh_token, then OAuth2RefreshToken is generated.
    id_token, then OidcIdToken is generated.
* code:生成授权码
* access_token:生成access tokn
* refresh_token:生成refresh_token
* id_token:生成OidcIdToken

Furthermore, the format of the generated OAuth2AccessToken varies, 
depending on the TokenSettings.getAccessTokenFormat() configured 
for the RegisteredClient. If the format is OAuth2TokenFormat.SELF_CONTAINED 
(the default), then a Jwt is generated. If the format is 
OAuth2TokenFormat.REFERENCE, then an "opaque" token is generated.
* TokenSettings.getAccessTokenFormat()可配置OAuth2AccessToken的格式
* OAuth2TokenFormat.SELF_CONTAINED:默认,生成jwt
* OAuth2TokenFormat.REFERENCE:生成opaque

Finally, if the generated OAuth2Token has a set of claims and 
implements ClaimAccessor, the claims are made accessible from 
OAuth2Authorization.Token.getClaims().
* 如果OAuth2Token中有claims、实现了ClaimAccessor接口
* 可通过OAuth2Authorization.Token.getClaims()获取

The OAuth2TokenGenerator is primarily used by components that 
implement authorization grant processing – for example, 
authorization_code, client_credentials, and refresh_token.
* OAuth2TokenGenerator主要在授权时使用

The provided implementations are OAuth2AccessTokenGenerator, 
OAuth2RefreshTokenGenerator, and JwtGenerator. The 
OAuth2AccessTokenGenerator generates an "opaque" 
(OAuth2TokenFormat.REFERENCE) access token, and the JwtGenerator 
generates a Jwt (OAuth2TokenFormat.SELF_CONTAINED)
* 默认提供的实现类:OAuth2AccessTokenGenerator、OAuth2RefreshTokenGenerator、JwtGenerator
* 格式为:OAuth2TokenFormat.REFERENCE,使用OAuth2AccessTokenGenerator生成token
* 格式为:OAuth2TokenFormat.SELF_CONTAINED,使用JwtGenerator生成token


The OAuth2TokenGenerator is an OPTIONAL component and defaults 
to a DelegatingOAuth2TokenGenerator composed of an 
OAuth2AccessTokenGenerator and OAuth2RefreshTokenGenerator
* Auth2TokenGenerator可选,如果不设置,默认为DelegatingOAuth2TokenGenerator
* DelegatingOAuth2TokenGenerator时组合生成器,包含了OAuth2AccessTokenGenerator
* OAuth2RefreshTokenGenerator

if a JwtEncoder @Bean or JWKSource<SecurityContext> @Bean is 
registered, then a JwtGenerator is additionally composed in the 
DelegatingOAuth2TokenGenerator
* 如果注册了JwtEncoder、JWKSource实例,
* JwtGenerator会自动添加到DelegatingOAuth2TokenGenerator中

The OAuth2TokenGenerator provides great flexibility, as it can 
support any custom token format for access_token and refresh_token
* OAuth2TokenGenerator支持自定义token格式

             

OAuth2TokenGenerator配置

// 方式1:注册bean
@Bean
public OAuth2TokenGenerator<?> tokenGenerator() {
	JwtEncoder jwtEncoder = ...
	JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
	OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
	OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
	return new DelegatingOAuth2TokenGenerator(
			jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
}

//方式2:OAuth2AuthorizationServerConfigurer注册
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
	OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
		new OAuth2AuthorizationServerConfigurer<>();
	http.apply(authorizationServerConfigurer);

	authorizationServerConfigurer
		.tokenGenerator(tokenGenerator);

	...

	return http.build();
}

              

OAuth2TokenCustomizer

An OAuth2TokenCustomizer provides the ability to customize the 
attributes of an OAuth2Token, which are accessible in the provided OAuth2TokenContext. It is used by an OAuth2TokenGenerator to let 
it customize the attributes of the OAuth2Token before it is generated.
* OAuth2TokenCustomizer可用来自定义OAuth2Token的attributes属性
* OAuth2TokenCustomizer设置到OAuth2TokenGenerator中

An OAuth2TokenCustomizer<OAuth2TokenClaimsContext> declared with a 
generic type of OAuth2TokenClaimsContext (implements OAuth2TokenContext) 
provides the ability to customize the claims of an "opaque" OAuth2AccessToken. 
OAuth2TokenClaimsContext.getClaims() provides access to the 
OAuth2TokenClaimsSet.Builder, allowing the ability to add, replace, 
and remove claims
* OAuth2TokenCustomizer<OAuth2TokenClaimsContext>可用来设置
* opaque类型的OAuth2AccessToken

If the OAuth2TokenGenerator is not provided as a @Bean or is not 
configured through the OAuth2AuthorizationServerConfigurer, an 
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> @Bean will automatically 
be configured with an OAuth2AccessTokenGenerator
* 如果没有注册OAuth2TokenGenerator实例bean、使用OAuth2AuthorizationServerConfigurer注册
* OAuth2TokenCustomizer<OAuth2TokenClaimsContext>会自动关联OAuth2AccessTokenGenerator


An OAuth2TokenCustomizer<JwtEncodingContext> declared with a generic type 
of JwtEncodingContext (implements OAuth2TokenContext) provides the ability 
to customize the headers and claims of a Jwt. JwtEncodingContext.getHeaders() 
provides access to the JwsHeader.Builder, allowing the ability to add, replace, 
and remove headers. JwtEncodingContext.getClaims() provides access to the 
JwtClaimsSet.Builder, allowing the ability to add, replace, and remove claim
* OAuth2TokenCustomizer<JwtEncodingContext>可自定义jwt的headers、claims
* JwtEncodingContext.getHeaders()获取JwsHeader.Builder,可添加、替换、删除headers
* JwtEncodingContext.getClaims()获取JwtClaimsSet.Builder,可添加、替换、删除claims

If the OAuth2TokenGenerator is not provided as a @Bean or is not 
configured through the OAuth2AuthorizationServerConfigurer, an OAuth2TokenCustomizer<JwtEncodingContext> @Bean will automatically 
be configured with a JwtGenerator
* 如果没有注册OAuth2TokenGenerator实例bean、使用OAuth2AuthorizationServerConfigurer注册
* OAuth2TokenCustomizer<JwtEncodingContext>会自动关联JwtGenerator

              

opaque token自定义属性

@Bean
public OAuth2TokenGenerator<?> tokenGenerator() {
	JwtEncoder jwtEncoder = ...
	JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
	OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
	accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer());
                         //自定义的token格式
	OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
	return new DelegatingOAuth2TokenGenerator(
			jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
}

@Bean
public OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer() {
	return context -> {
		OAuth2TokenClaimsSet.Builder claims = context.getClaims();
		// Customize claims

	};
}

       

jwt token自定义属性

@Bean
public OAuth2TokenGenerator<?> tokenGenerator() {
	JwtEncoder jwtEncoder = ...
	JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
	jwtGenerator.setJwtCustomizer(jwtCustomizer());
	OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
	OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
	return new DelegatingOAuth2TokenGenerator(
			jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
}

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
	return context -> {
		JwsHeader.Builder headers = context.getHeaders();
		JwtClaimsSet.Builder claims = context.getClaims();
		if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
			// Customize headers/claims for access_token

		} else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
			// Customize headers/claims for id_token

		}
	};
}

         

               

                                    

uri 授权路径

          

ProviderSettings contains the configuration settings for the OAuth2 
authorization server (provider). It specifies the URI for the protocol 
endpoints as well as the issuer identifier
* ProviderSettings设置了OAuth2授权服务器端点uri、issuer identifier配置

ProviderSettings is a REQUIRED component
* ProviderSettings必须设置

@Import(OAuth2AuthorizationServerConfiguration.class) automatically 
registers a ProviderSettings @Bean, if not already provided
* 如果没有设置,OAuth2AuthorizationServerConfiguration会自动导入

          

默认 uri

public final class ProviderSettings extends AbstractSettings {

	...

	public static Builder builder() {
		return new Builder()
			.authorizationEndpoint("/oauth2/authorize")
			.tokenEndpoint("/oauth2/token")
			.tokenIntrospectionEndpoint("/oauth2/introspect")
			.tokenRevocationEndpoint("/oauth2/revoke")
			.jwkSetEndpoint("/oauth2/jwks")
			.oidcUserInfoEndpoint("/userinfo")
			.oidcClientRegistrationEndpoint("/connect/register");
	}

	...

}

      

自定义 uri

@Bean
public ProviderSettings providerSettings() {
	return ProviderSettings.builder()
		.issuer("https://example.com")
		.authorizationEndpoint("/oauth2/v1/authorize")
		.tokenEndpoint("/oauth2/v1/token")
		.tokenIntrospectionEndpoint("/oauth2/v1/introspect")
		.tokenRevocationEndpoint("/oauth2/v1/revoke")
		.jwkSetEndpoint("/oauth2/v1/jwks")
		.oidcUserInfoEndpoint("/connect/v1/userinfo")
		.oidcClientRegistrationEndpoint("/connect/v1/register")
		.build();
}

             

                   

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值