Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to treat the certification process of Spring security oauth2

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This issue of the content of the editor will bring you about how to view the Spring security oauth2 certification process, the article is rich in content and professional analysis and description for you, after reading this article, I hope you can get something.

Spring Security OAuth3 finishing

Implicit Authorization Mode (Implicit Grant)

The parameter address to be provided: oauth/token request header parameter: Authorization=Basic base64.encode (client_id:client_secret) = = if secret is empty, only client_id is encoded = = POST parameter grant_type:password username: username password: password

Client_credentials certification

Parameter address to be passed: oauth/token Header parameter client_id:client_secret: Header header add Authorization=Basic base64.encode (client_id:client_secret) = = if secret is empty, only client_id is encoded = = Post parameter grant_type: password scope: scope

Password mode

The parameter address to be passed: oauth/token Header parameter client_id:client_secret: Header header add Authorization=Basic base64.encode (client_id:client_secret) = = if secret is empty, only client_id is encoded = = Post parameter grant_type: password username: username password: password scope: scope

Authorization code mode

1. First request oauth/authorize to get the parameters to be submitted for code: Header parameter client_id:client_secret: Header header add Authorization=Basic base64.encode (client_id:client_secret) if secret is empty, only encode the client_id parameter post parameter grant_type: password username: username password: password scope: scope 2. Access the oauth/token interface through code in exchange for the accessTokenSpring Security OAuth3 authentication process of response

First open the @ EnableAuthorizationServer annotation

AuthorizationServerConfigurerAdapterm default method configuration

Public class AuthorizationServerConfigurerAdapter implements AuthorizationServerConfigurer {@ Override public void configure (AuthorizationServerSecurityConfigurer security) throws Exception {/ / configure AuthorizationServer security authentication related information, create ClientCredentialsTokenEndpointFilter core filter} @ Override public void configure (ClientDetailsServiceConfigurer clients) throws Exception {/ / configure OAuth3 client related information} @ Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) throws Exception {/ / configure AuthorizationServerEndpointsConfigurer many related classes, including configuring authenticator, configuring authentication method TokenStore,TokenGranter,OAuth3RequestFactory}

Client authentication core filter ClientCredentialsTokenEndpointFilter

The core code is as follows

Public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {... String clientId = request.getParameter ("client_id"); String clientSecret = request.getParameter ("client_secret"); ClientId = clientId.trim (); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (clientId, clientSecret); return this.getAuthenticationManager (). Authenticate (authRequest)

Top identity Manager AuthenticationManager

Get the client_id,client_secret from the request, assemble a UsernamePasswordAuthenticationToken as the identity, and use the top-level identity manager AuthenticationManager in the container to authenticate (the implementation class of AuthenticationManager is usually ProviderManager. While ProviderManager maintains a List internally, the real identity authentication is accomplished by a series of AuthenticationProvider. The common implementation class of AuthenticationProvider is the aggregation of a UserDetailsService interface inside DaoAuthenticationProvider,DaoAuthenticationProvider, and UserDetailsService is the final interface to obtain user details.

There is no concept of "user" in client mode, so what is authentication here? Debug can find that the implementation of UserDetailsService is adapted to ClientDetailsUserDetailsService. This design adapts the information of the client client (client_id,client_secret) to the user's information (username,password). After ClientCredentialsTokenEndpointFilter, the identity information has been verified by AuthenticationManager. And then arrived.

TokenEndpoint .

Token processing endpoint TokenEndpoint

The first two ClientCredentialsTokenEndpointFilter and AuthenticationManager can be understood as some pre-verification, and identity encapsulation

@ FrameworkEndpointpublic class TokenEndpoint extends AbstractEndpoint {@ RequestMapping (value = "/ oauth/token", method=RequestMethod.POST) public ResponseEntity postAccessToken (Principal principal, @ RequestParam Map parameters) throws HttpRequestMethodNotSupportedException {... String clientId = getClientId (principal); ClientDetails authenticatedClient = getClientDetailsService () .loadClientByClientId (clientId); / / load client information. TokenRequest tokenRequest = getOAuth3RequestFactory () .createTokenRequest (parameters, authenticatedClient); / / create a TokenRequest with the request information. OAuth3AccessToken token = getTokenGranter (). Grant (tokenRequest.getGrantType (), tokenRequest); / / pass TokenRequest to TokenGranter to issue token. Return getResponse (token);} private TokenGranter tokenGranter

The real / oauth/token endpoint, where the Principal in the method parameters has been populated with the relevant information through the previous filter, and the interior of the method relies on a TokenGranter to issue the token. Where the implementation class DefaultOAuth3AccessToken of OAuth3AccessToken is the original class before the token serialization that is finally obtained on the console:

Public class DefaultOAuth3AccessToken implements Serializable, OAuth3AccessToken {private static final long serialVersionUID = 914967629530462926L; private String value; private Date expiration; private String tokenType = BEARER_TYPE.toLowerCase (); private OAuth3RefreshToken refreshToken; private Set scope; private Map additionalInformation = Collections.emptyMap () / / getter,setter} @ org.codehaus.jackson.map.annotate.JsonSerialize (using = OAuth3AccessTokenJackson1Serializer.class) @ org.codehaus.jackson.map.annotate.JsonDeserialize (using = OAuth3AccessTokenJackson1Deserializer.class) @ com.fasterxml.jackson.databind.annotation.JsonSerialize (using = OAuth3AccessTokenJackson2Serializer.class) @ com.fasterxml.jackson.databind.annotation.JsonDeserialize (using = OAuth3AccessTokenJackson2Deserializer.class) public interface OAuth3AccessToken {public static String BEARER_TYPE = "Bearer"; public static String OAUTH2_TYPE = "OAuth3" / * The access token issued by the authorization server. This value is REQUIRED. * / public static String ACCESS_TOKEN = "access_token"; / * The type of the token issued as described in Section 7.1. Value is case insensitive. * This value is REQUIRED. * / public static String TOKEN_TYPE = "token_type"; / * * The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will * expire in one hour from the time the response was generated. This value is OPTIONAL. * / public static String EXPIRES_IN = "expires_in"; / * The refresh token which can be used to obtain new access tokens using the same authorization grant as described * in Section 6. This value is OPTIONAL. * / public static String REFRESH_TOKEN = "refresh_token"; / * The scope of the access token as described by Section 3.3* / public static String SCOPE = "scope";

TokenGranter

The design idea of TokenGranter is to use CompositeTokenGranter to manage a List list, and each grantType corresponds to a specific real authorized person. In the process of debug, it can be found that CompositeTokenGranter invokes the grant methods of five TokenGranter implementation classes in a loop, while granter uses grantType to distinguish whether it is their respective authorization type or not.

Public class CompositeTokenGranter implements TokenGranter {private final List tokenGranters; public CompositeTokenGranter (List tokenGranters) {this.tokenGranters = new ArrayList (tokenGranters);} public OAuth3AccessToken grant (String grantType, TokenRequest tokenRequest) {for (TokenGranter granter: tokenGranters) {OAuth3AccessToken grant = granter.grant (grantType, tokenRequest); if (grantless null) {return grant;}} return null }}

The five types are:

ResourceOwnerPasswordTokenGranter = > password password mode

AuthorizationCodeTokenGranter = > authorization_code authenticator mode

ClientCredentialsTokenGranter = > client_credentials client mode

ImplicitTokenGranter = > implicit simplified mode

RefreshTokenGranter = = > refresh_token Refresh token only

Taking the client mode as an example, to think about how to generate token, we need to continue to study the abstract classes of five licensors: AbstractTokenGranter.

Public abstract class AbstractTokenGranter implements TokenGranter {protected final Log logger = LogFactory.getLog (getClass ()); / / service related to token, focus on private final AuthorizationServerTokenServices tokenServices; / / service related to clientDetails, focus on private final ClientDetailsService clientDetailsService; / / create oauth3Request factory, focus on private final OAuth3RequestFactory requestFactory; private final String grantType;. Public OAuth3AccessToken grant (String grantType, TokenRequest tokenRequest) {... String clientId = tokenRequest.getClientId (); ClientDetails client = clientDetailsService.loadClientByClientId (clientId); validateGrantType (grantType, client); logger.debug ("Getting access token for:" + clientId); return getAccessToken (client, tokenRequest);} protected OAuth3AccessToken getAccessToken (ClientDetails client, TokenRequest tokenRequest) {return tokenServices.createAccessToken (getOAuth3Authentication (client, tokenRequest)) } protected OAuth3Authentication getOAuth3Authentication (ClientDetails client, TokenRequest tokenRequest) {OAuth3Request storedOAuth3Request = requestFactory.createOAuth3Request (client, tokenRequest); return new OAuth3Authentication (storedOAuth3Request, null);}.}

Key points of AuthorizationServerTokenServices analysis

Token operates service on AuthorizationServer. The API is designed as follows:

Public interface AuthorizationServerTokenServices {/ / create token OAuth3AccessToken createAccessToken (OAuth3Authentication authentication) throws AuthenticationException; / / Refresh token OAuth3AccessToken refreshAccessToken (String refreshToken, TokenRequest tokenRequest) throws AuthenticationException; / / get token OAuth3AccessToken getAccessToken (OAuth3Authentication authentication);}

In the default implementation class DefaultTokenServices, you can see how token is generated and what information the framework associates with token.

@ Transactionalpublic OAuth3AccessToken createAccessToken (OAuth3Authentication authentication) throws AuthenticationException {OAuth3AccessToken existingAccessToken = tokenStore.getAccessToken (authentication); OAuth3RefreshToken refreshToken = null; if (existingAccessToken! = null) {if (existingAccessToken.isExpired ()) {if (existingAccessToken.getRefreshToken ()! = null) {refreshToken = existingAccessToken.getRefreshToken () / / The token store could remove the refresh token when the / / access token is removed, but we want to / / be sure... TokenStore.removeRefreshToken (refreshToken);} tokenStore.removeAccessToken (existingAccessToken);} else {/ / Re-store the access token in case the authentication has changed tokenStore.storeAccessToken (existingAccessToken, authentication); return existingAccessToken;}} / / Only create a new refresh token if there wasn't an existing one / / associated with an expired access token. / / Clients might be holding existing refresh tokens, so we re-use it in / / the case that the old access token / / expired. If (refreshToken = = null) {refreshToken = createRefreshToken (authentication);} / But the refresh token itself might need to be re-issued if it has / / expired. Else if (refreshToken instanceof ExpiringOAuth3RefreshToken) {ExpiringOAuth3RefreshToken expiring = (ExpiringOAuth3RefreshToken) refreshToken; if (System.currentTimeMillis () > expiring.getExpiration (). GetTime ()) {refreshToken = createRefreshToken (authentication);}} OAuth3AccessToken accessToken = createAccessToken (authentication, refreshToken); tokenStore.storeAccessToken (accessToken, authentication); / / In case it was modified refreshToken = accessToken.getRefreshToken (); if (refreshToken! = null) {tokenStore.storeRefreshToken (refreshToken, authentication) } return accessToken;}

The role of AuthorizationServerTokenServices, which provides the implementation of creating token, refreshing token, and getting token. When creating a token, he will call the token and related information generated by the tokenStore pair to store in the corresponding implementation class, which can be redis, database, memory, jwt.

The above is the editor for you to share how to view the Spring security oauth2 authentication process, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report