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 gracefully add OAuth2 Protocol Authorization Model to Spring Security

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

Share

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

This article is about how Spring Security elegantly increases the authorization mode of OAuth2 agreement. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

What is the OAuth3 protocol?

OAuth 2.0 is an open network protocol about authorization, which is the most popular authorization mechanism at present.

The owner of the data told the system that it agreed to authorize third-party applications to enter the system and obtain the data. The system thus generates a short-term entry token (token), which is used instead of the password for use by third-party applications.

Due to the large number of authorization scenarios, the OAuth 2.0 protocol defines four authorization methods for obtaining tokens, namely:

Authorization code mode: authorization code mode (authorization code) is the most complete and rigorous authorization mode. Its characteristic is to interact with the authentication server of the "service provider" through the background server of the client.

Simplified mode: simplified mode (implicit grant type) applies for tokens directly from the authentication server in the browser without going through the server of the third-party application, skipping the step of "authorization code", hence the name. All the steps are done in the browser, the token is visible to the visitor, and the client does not require authentication.

Password mode: in password mode (Resource Owner Password Credentials Grant), the user provides his user name and password to the client. The client uses this information to ask the "service provider" for authorization.

Client mode: client mode (Client Credentials Grant) means that the client authenticates to the "service provider" in its own name, not in the name of the user. Strictly speaking, client-side mode is not a problem to be solved by the OAuth framework. In this mode, the user registers directly with the client, and the client requests the "service provider" to provide services in its own name, but there is no authorization problem.

Different grant_type is used to distinguish the four authorization modes.

Second, why customize the authorization type?

Although the OAuth3 protocol defines four standard authorization modes, it is still far from meeting a variety of abnormal business scenarios in the actual development process, and we need to expand it.

For example, add graphic verification code, mobile phone verification code, mobile phone number password login, and so on.

It is common to extend Spring Security authorization by adding a filter Filter, but there are two problems with this implementation:

Break away from the management of OAuth3

Inflexibility: for example, the system uses password mode authorization, and the web version needs to add graphic CAPTCHA verification, but when the mobile APP is not needed, it is more troublesome to use the method of adding Filter to implement.

So at present, the more elegant and flexible extension way in Spring Security is to add authorization mode through custom grant_type.

Third, the realization train of thought

Before expanding, we first need to understand the whole authorization process of Spring Security. I will take the password mode as an example to analyze it, as shown in the following figure.

3.1. Process analysis

The key points of the entire authorization process are divided into the following two parts:

The first part: the parsing of authorization type grant_type

Each grant_type has a corresponding TokenGranter implementation class.

All TokenGranter implementation classes are saved through the tokenGranters collection in CompositeTokenGranter.

Then determine which TokenGranter implementation class is used to handle authorization by determining the grantType parameter.

Part two: about authorization login logic

Each authorization method will have a corresponding AuthenticationProvider implementation class to implement.

All AuthenticationProvider implementation classes are saved through the providers collection in ProviderManager.

The TokenGranter class new an AuthenticationToken implementation class, such as UsernamePasswordAuthenticationToken to the ProviderManager class.

ProviderManager uses AuthenticationToken to determine which AuthenticationProvider implementation class is used to handle authorization.

The specific login logic is implemented by the AuthenticationProvider implementation class, such as DaoAuthenticationProvider.

3.2. Extended analysis

According to the above process, the extension is divided into the following two scenarios

Scenario 1: only enhance or expand the original authorization logic, such as adding graphic verification code before login of user name and password.

In this scenario, you need to define a new grantType type, add the corresponding TokenGranter implementation class to add extension content, and then add it to the tokenGranters collection in CompositeTokenGranter.

Reference code: PwdImgCodeGranter.java

Scenario 2: add a new authorization method, such as: mobile phone number plus password login.

The scenario needs to implement the following:

Define a new grantType type and add the corresponding TokenGranter implementation class to the tokenGranters collection in CompositeTokenGranter

A new AuthenticationToken implementation class is added to store the information needed for the authorization.

Add a new AuthenticationProvider implementation class to implement the authorization logic, and override the AuthenticationToken implementation class of step 2 of supports method binding

Reference code: MobilePwdGranter.java

Fourth, code implementation

The following example shows the core code implementation by adding a new mobile number plus password authorization in scenario 2.

4.1. Create an AuthenticationToken implementation class

Create a MobileAuthenticationToken class to store mobile phone number and password information

Public class MobileAuthenticationToken extends AbstractAuthenticationToken {private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Object principal; private Object credentials; public MobileAuthenticationToken (String mobile, String password) {super (null); this.principal = mobile; this.credentials = password; setAuthenticated (false) } public MobileAuthenticationToken (Object principal, Object credentials, Collection authentication) {return MobileAuthenticationToken.class.isAssignableFrom (authentication);} 4.3. Create a TokenGranter implementation class

Create the MobilePwdGranter class and define the value of grant_type as mobile_password

Public class MobilePwdGranter extends AbstractTokenGranter {private static final String GRANT_TYPE = "mobile_password"; private final AuthenticationManager authenticationManager; public MobilePwdGranter (AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth3RequestFactory requestFactory) {super (tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); this.authenticationManager = authenticationManager;} @ Override protected OAuth3Authentication getOAuth3Authentication (ClientDetails client, TokenRequest tokenRequest) {Map parameters = new LinkedHashMap (tokenRequest.getRequestParameters ()) String mobile = parameters.get ("mobile"); String password = parameters.get ("password"); parameters.remove ("password"); Authentication userAuth = new MobileAuthenticationToken (mobile, password); ((AbstractAuthenticationToken) userAuth) .setDetails (parameters); userAuth = authenticationManager.authenticate (userAuth); if (userAuth = = null | |! userAuth.isAuthenticated ()) {throw new InvalidGrantException ("Could not authenticate mobile:" + mobile) } OAuth3Request storedOAuth3Request = getRequestFactory (). CreateOAuth3Request (client, tokenRequest); return new OAuth3Authentication (storedOAuth3Request, userAuth);} Add to the collection in CompositeTokenGranter / / add cell phone number and password authorization mode tokenGranters.add (new MobilePwdGranter (authenticationManager, tokenServices, clientDetailsService, requestFactory)); 4.5. test

Use the following address to specify that grant_type is mobile_password for authorization to obtain access_token

/ oauth/token?grant_type=mobile_password&mobile= {mobile} & password= {password}

This is how Spring Security elegantly adds the OAuth2 protocol authorization model, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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