Spring security + Oauth2 authentication solution: project configuration and testing

This project uses Spring security + Oauth2 to complete user authentication and user authorization. Spring security is a powerful and highly customizable authentication
and access control framework. The Spring security framework integrates the Oauth2 protocol. The following figure is the project authentication architecture diagram:

1. The user requests the authentication service to complete the authentication.
2. The authentication service issues the user's identity token, and having an identity token indicates that the identity is legal.
3. The user carries the token to request the resource service, and the request for the resource service must first go through the gateway.
4. The gateway verifies the validity of the user's identity token. If it is not valid, it means that the user has not logged in. If it is valid, it will allow the user to continue accessing.
5. The resource service obtains the token and completes authorization based on the token.
6. The resource service responds to the resource information after the authorization is completed.

Oauth2 authorization code mode

Oauth2 authorization mode

Oauth2 has the following authorization modes:
authorization code mode (Authorization Code),
implicit authorization mode (Implicit),
password mode (Resource Owner Password Credentials),
client mode (Client Credentials)
, among which authorization code mode and password mode are widely used, this section introduces authorization code mode.

Authorization code authorization process

The process of using WeChat authentication on the Dark Horse programmer website listed above is the authorization code mode, and the process is as follows:
1. The client requests third-party authorization
2. The user (resource owner) agrees to authorize the client
3. The client obtains the authorization code , Request the authentication server to apply for a token
4. The authentication server responds to the client with a token
5. The client requests resources from the resource server, and the resource service verifies the validity of the token to complete the authorization
6. The resource server returns the protected resource

Apply for an authorization code

Request the authentication service to get the authorization code:
Get request:

curl localhost:40400/auth/oauth/authorize?client_id=XcWebApp&response_type=code&scop=app&redirect_uri=http://localhost

The parameter list is as follows:

  • client_id: client id, which is consistent with the client id set in the authorization configuration class.
  • response_type: the authorization code mode is fixed to code
  • scop: client scope, which is consistent with the scop set in the authorization configuration class.
  • redirect_uri: redirect uri, when the authorization code application is successful, it will jump to this address, and the code parameter (authorization code) will be attached behind it.
    First jump to the login page:

insert image description here

Enter the account and password, and click Login.
When Spring Security receives the request, it will call the loadUserByUsername method of the UserDetailsService interface to query the user's correct password.
The correct password is hard-coded as "123" in the currently imported basic project, so enter the account number here, and enter 123 as the password to pass the authentication.
Then enter the authorization page:
insert image description here

Click "Agree".
Then return the authorization code:
the authentication service carries the authorization code and jumps to redirecturi
insert image description here

Apply for a token

After getting the authorization code, apply for a token.
Post request: http://localhost:40400/auth/oauth/token
The parameters are as follows:

  • grant_type: authorization type, fill in authorization_code, indicating the authorization code mode
  • code: Authorization code, which is the authorization code you just obtained. Note: the authorization code will be invalid after being used only once, and you need to apply again.
  • redirect_uri: The redirect url when applying for the authorization code must be consistent with the redirect_uri used when applying for the authorization code.
    This link needs to use http Basic authentication.
    What is http Basic authentication?
    An authentication method defined by the http protocol. The client id and client password are spliced ​​according to the format of "client ID: client password", encoded with base64, and placed in the header to request the server. An example: Authorization
    :
    Basic WGNXZWJBcHA6WGNXZWJBcHA=WGNXZWJBcHA6WGNXZWJBcHA=Username: base64 encoding of password.
    The authentication fails and the server returns 401 Unauthorized.
    The above tests are completed using postman:
    http basic authentication:
    insert image description here
    the client ID and client password will match the client ID and client password in the database oauthclientdetails table.
    Post request parameters:
    insert image description here
    Click to send:
    Apply for token successfully:
    insert image description here
    access_token: Access token, carry this token to access resources
    token_type: There are two types of MAC Token and Bearer Token, and the verification algorithms of the two are different. RFC 6750 recommends that Oauth2 use Bearer Token ( http://www.rfcreader.com/#rfc6750).
    refresh_token: Refresh token, use this token to extend the expiration time of the access token.
    expires_in: Expiration time, in seconds.
    scope: scope, consistent with the defined client scope.

Resource Service Authorization

Resource service authorization process
The resource service has the protected resources to be accessed. The client carries a token to access the resource service. If the token is legal, the resources in the resource service can be successfully accessed, as shown in the following figure:
insert image description here

The business process in the above figure is as follows:
1. The client requests the authentication service to apply for a token.
2. The authentication service generates a token.
The authentication service uses an asymmetric encryption algorithm and uses a private key to generate a token.
3. The client carries the token to access the resource service.
The client adds in the Http header: Authorization: Bearer token.
4. The resource service requests the authentication service to verify the validity of the token.
The resource service receives the token and uses the public key to verify the validity of the token.
5. The token is valid, and the resource service responds to the client with resource information

Resource service authorization configuration
Basically all microservices are resource services. Here we configure authorization control on the course management service. After the authorization control is configured, if you want to access course information, you must provide a token.
1. Configure the public key
The authentication service generates tokens using an asymmetric encryption algorithm, the authentication service uses private key encryption to generate tokens, and provides the public key to the resource service, and the resource service uses the public key to verify the legitimacy of the token.
Copy the public key to the publickey.txt file, and copy this file to the classpath of the resource service project
insert image description here

2. Add dependencies

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring‐cloud‐starter‐oauth2</artifactId>
</dependency>

3. Create the ResourceServerConfig class under the config package:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的
PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
    
	//公钥
	private static final String PUBLICKEY = "publickey.txt";
	//定义JwtTokenStore,使用jwt令牌
	@Bean
	public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
    
    
		return new JwtTokenStore(jwtAccessTokenConverter);
	}
	//定义JJwtAccessTokenConverter,使用jwt令牌
	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter() {
    
    
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		converter.setVerifierKey(getPubKey());
		return converter;
	}
	/**
	* 获取非对称加密公钥 Key
	* @return 公钥 Key
	*/
	private String getPubKey() {
    
    
		Resource resource = new ClassPathResource(PUBLIC_KEY);
		try {
    
    
			InputStreamReader inputStreamReader = new
			InputStreamReader(resource.getInputStream());
			BufferedReader br = new BufferedReader(inputStreamReader);
			return br.lines().collect(Collectors.joining("\n"));
		} catch (IOException ioe) {
    
    
			return null;
		}
	}
	//Http安全配置,对每个到达系统的http请求链接进行校验
	@Override
	public void configure(HttpSecurity http) throws Exception {
    
    
		//所有请求必须认证通过
		http.authorizeRequests().anyRequest().authenticated();
	}
}

Resource Service Authorization Test

Here we test course image query

get http://localhost:31200/course/coursepic/list/4028e58161bd3b380161bd3bcd2f0000

If the request does not carry the token, an error will be reported:

{
    
    
	"error": "unauthorized",
	"error_description": "Full authentication is required to access this resource"
}

Carry the token when requesting:
Add Authorization in the http header: Bearer token
insert image description here

When the wrong token is entered, resources cannot be accessed normally.

insert image description here

Solve swagger-ui can not be accessed

When the course management adds authorization and then access swagger-ui, an error will be reported:
insert image description here
modify the configure method of the authorization configuration class ResourceServerConfig:
release the request path for swagger-ui:

//Http安全配置,对每个到达系统的http请求链接进行校验
@Override
public void configure(HttpSecurity http) throws Exception {
    
    
	//所有请求必须认证通过
	http.authorizeRequests()
	//下边的路径放行
	.antMatchers("/v2/api‐docs", "/swagger‐resources/configuration/ui",
	"/swagger‐resources","/swagger‐resources/configuration/security",
	"/swagger‐ui.html","/webjars/**").permitAll()
	.anyRequest().authenticated();
}

Note:
Although swagger-ui can be accessed through the above configuration, unit testing cannot be performed unless the authentication configuration is removed or all
requests are allowed ("/**") added to the above configuration.

Guess you like

Origin blog.csdn.net/a772304419/article/details/132084122