(11) Integrate spring cloud cloud architecture - OAuth2.0 login authentication for SSO single sign-on (1)

I wrote a lot of articles about spring cloud before. Today, we will take notes on the integration of OAuth2.0. First, I found some basic knowledge points about OAuth2.0 from the Internet to help you review the knowledge points:

 

1. Roles in oauth

client : the application that calls the resource server API

Oauth 2.0 Provider : including Authorization Server and Resource Server

(1) Authorization Server: Authentication server for authentication and authorization

(2) Resource Server: resource server, protecting protected resources
user : resource owner

 

Second, the following describes the Oauth 2.0 Provider in detail

Authorization Server:

(1)AuthorizationEndpoint:进行授权的服务,Default URL: /oauth/authorize

(2) TokenEndpoint : Service for obtaining token, Default URL: /oauth/token  

Resource Server:

OAuth2AuthenticationProcessingFilter : Loads authentication for requests with access tokens

 

Third, let's introduce the Authorization Server in detail:

In general, create two configuration classes, one inherits AuthorizationServerConfigurerAdapter, the other inherits WebSecurityConfigurerAdapter, and then overwrite the methods inside.

There are two main types of annotations:

1. @EnableAuthorizationServer: Declare an authentication server. When this annotation is used, several Endpoints will be automatically generated after the application starts : (Note: In fact, implementing an authentication server is as simple as adding an annotation. Of course, it is really used in the production environment Still have to do some configuration and replication work.)

/oauth/authorize:验证

/ oauth / token: 获tori token

/oauth/confirm_access: user authorization

/oauth/error: Authentication failed

/oauth/check_token: used by the resource server to verify the token

/oauth/token_key: if in jwt mode, this can be used to get the public key from the authentication server

The above endpoints are all in the endpoint package in the source code.

 

2. @Beans: AuthorizationServerConfigurer needs to be implemented

AuthorizationServerConfigurer contains three configurations:

ClientDetailsServiceConfigurer: The information configuration of the client client, the client information includes: clientId, secret, scope, authorizedGrantTypes, authorities

(1) scope: Indicates the scope of authority, optional items, which can be selected when the user authorizes the page

(2) authorizedGrantTypes: There are four authorization methods 

  • Authorization Code: Use verification to get the code, and then use the code to get the token (the most used way and the safest way)
  • Implicit: Implicit Grant Mode
  • Client Credentials (used to get App Access Token)
  • Resource Owner Password Credentials

(3) authorities: the authority granted to the client

 

There are many specific implementations here, in-memory, JdbcClientDetailsService, jwt, etc.

AuthorizationServerSecurityConfigurer: Declare security constraints, which allow access and which are not allowed

AuthorizationServerEndpointsConfigurer: Declare authorization and token endpoints and some configuration information of token services, such as what storage method is used, token validity period, etc.

 

Reading of client information: Configure it in the ClientDetailsServiceConfigurer class, and there can be multiple reading methods such as in-memory and jdbc.

jdbc needs to call the JdbcClientDetailsService class, which needs to pass in the corresponding DataSource.

 

Here's how to manage tokens:

AuthorizationServerTokenServices接口:声明必要的关于token的操作

(1) When the token is created, save it so that future resources that accept the access token can refer to it.

(2) The access token is used to load the authentication

There are also many implementations of the interface.DefaultTokenServices是其默认实现,他使用了默认的InMemoryTokenStore,不会持久化token;

 

There are three ways of token storage:

(1) InMemoryTokenStore: Stored in memory and will not persist

(2) JdbcTokenStore: stored in the database

(3)Jwt: json web token

 

Authorization Type:

It can be configured through the AuthorizationServerEndpointsConfigurer. By default, all authorization types except passwords are supported. Some classes of related grant types:

(1) AuthenticationManager: Directly inject an AuthenticationManager to automatically open the password authorization type

(2) userDetailsService: If UserDetailsService is injected, it will start to refresh the token authorization type, and it will determine whether the user is still alive

(3) authorizationCodeServices: an instance of AuthorizationCodeServices, a service of auth code authorization type

(4)implicitGrantService:imlpicit grant

(5)tokenGranter:

 

Configuration of the URL of the endpoint:

(1) The pathMapping() method of AuthorizationServerEndpointsConfigurer has two parameters, the first is the default URL path, and the second is the custom path

(2) An instance of WebSecurityConfigurer can configure which paths do not require protection and which require protection. All are protected by default.

 

Custom UI:

(1) Sometimes, we may need customized login pages and authentication pages. For the login page, you only need to create a web page with login as the prefix name. In the code, set it to allow access, so that the system will automatically execute your login page. Pay attention to the action of this landing page, it must be a jump to the certified address.

(2) The other is the authorization page, which allows you to check the options. This page can refer to the implementation in the source code, generate a controller class by yourself, and then create a corresponding web page to implement custom functions.

 

Let's sort out the authorization and acquisition token process:

(1) Replace the port number with the port number of your own authentication server, and replace the client_id with your own, and the response_type type is code.

 localhost:8080/uaa/oauth/authorize?client_id=client&response_type=code&redirect_uri= http://www .baidu.com
(2) At this time you will get a code value: http://www .baidu.com/?code= G0C20Z

(3) Use this code value to get the final token:

curl -X POST -H "Cant-Type: application/x-www-form-urlencoded" -d 'grant_type=authorization_code&code=G0C20Z&redirect_uri=http://www.baidu.com' "http://client:secret@localhost:8080/uaa/oauth/token"

return value:

{"access_token":"b251b453-cc08-4520-9dd0-9aedf58e6ca3","token_type":"bearer","expires_in":2591324,"scope":"app"}

 

(4) Use this token value to call the resource server content (if the resource server and the authentication server are in the same application, the resource server will parse the token value by itself, if not, then you have to do it yourself)

curl -H "Authorization: Bearer b251b453-cc08-4520-9dd0-9aedf58e6ca3" "localhost:8081/service2 (replace your own url here)"

 

Fourth, Resource Server: protect resources, need a token to access

Add the annotation @EnableResourceServer to the configuration class to start. Use ResourceServerConfigurer to configure:

(1) tokenServices: an instance of ResourceServerTokenServices, which declares token services

(2) resourceId: Resource Id, verified by auth Server.

(3) Some other extension points, such as tokenExtractor that can extract tokens from requests

(4) Some custom resource protection configurations are set through HttpSecurity

 

There are also two ways to use tokens:

(1) Bearer Token (https transmission method ensures the security of the transmission process): mainstream

(2)Mac(http+sign)

 

How to access API in resource server?

If the resource server and authorization server are in the same application, and you use DefaultTokenServices, you don't have to think about this too much, because it implements all the necessary interfaces, so it's automatically consistent. If your resource server is a separate application, then you must make sure you match the capabilities of the authorization server and provide ResourceServerTokenServices that know how to properly decode the token. As with authorization servers, you can often use DefaultTokenServices, and options are mostly represented via a TokenStore (backend store or local encoding).

(1) When verifying the token in the request, use RemoteTokenServices to call /auth/check_token in AuthServer.

(2) Share the database, use Jdbc to store and verify the token, and avoid accessing the AuthServer again.

(3) Using the JWT signature method, the resource server performs the verification directly without any intermediary.

 

Five, oauth client

After the client obtains the token, when it wants to call the downstream service API, in order to pass the token, it can use RestTemplate. Then use restTemplate to call the Api.

Note:

The difference between scopes and authorities:

Scopes are client permissions, grant at least one scope permission, otherwise an error will be reported.

authorities are user rights.   

The above is a good blog I found on the Internet. I hope it can help you quickly understand OAuth2.0. In the next article, we will formally introduce the use of OAuth2.0 in the current framework. 

 

From now on, I will record the construction process and essence of the recently developed spring cloud microservice cloud architecture to help more friends who are interested in developing the spring cloud framework. Let's discuss the construction process and how of the spring cloud architecture together. Used in enterprise projects.

Sources of information and source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324396444&siteId=291194637