Online studies - Day 16 - Lecture - Spring Security Oauth2 JWT four

3.3.3  claim token 
get the authorization code, claim token. 
Post request : HTTP: // localhost: 40400 / auth / oauth / token 
parameters are as follows: 
grant_type : authorization type, fill authorization_code , express authorization code pattern 
code : Authorization Code, that is, just get the authorization code Note: The authorization code is only used once invalid, need to re-apply. 
redirect_uri : Jump on the application of the authorization code url , and with a certain time of application authorization code redirect_uri consistent. 
This link requires  http Basic Authentication. 
What is http Basic Authentication? 
http authentication method defined in the protocol, the client id and password as client " Client ID: Client password " format stitching, and with base64 encoding code, on the headerRequesting server, an example:
the Authorization : Basic WGNXZWJBcHA6WGNXZWJBcHA =
WGNXZWJBcHA6WGNXZWJBcHA =  username : password base64 encoding. 
Authentication failed server returns the  401 Unauthorized 
above tests using postman complete: 
HTTP Basic authentication:
 

 
the access_token : access token, carries this token to access resources 
token_type : There MAC Token and Bearer Token two types, two different calibration algorithms, RFC 6750 recommended Oauth2 using  Bearer Token ( http://www.rfcreader.com/#rfc6750 ).
refresh_token : refresh token can use this token to extend the expiration time access token. 
expires_in : expiration time, in seconds. 
scope : range, consistent with client-defined range.
3.3.4  Resource Services Licensing
3.3.4.1  Resources Services Licensing Process 
Resource Service have access to protected resources, client service carries a token to access a resource, if the token funding lawful can successfully access resources service source, as shown below: 

 
FIG on business processes as follows:

1 , the client requests authentication token service application 
2 , generates token authentication service 
authentication service using an asymmetric encryption algorithm, using the secret key generation token. 
3 , the client carries a token to access a resource service 
clients Http header  added in:  the Authorization : Bearer  token. 
4 , the service request authentication service resource check the validity of the token 
resource service token is received, the legitimacy of the public key used to verify the token. 
5 , the token is valid, the resource services to clients in response to resource information 
3.3.4.2  Resources services authorization configuration 
substantially all of the services are micro-resource services, where we configure authorization control on the course management service, when configured with authorization To control access course believe the information you must provide the token.
1 , the public key configuration 
Generating token authentication service using an asymmetric encryption algorithm, using the private key to generate the service authentication token to the resource outside of the public key services, resources allows the legitimacy of the public key used to verify the token.
Copy the public key to  publickey.txt file, copy this file to the resource service project classpath under 

 
2 , add dependencies

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

4 , in confifig created under the package ResourceServerConfifig categories:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的
PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
//公钥
private static final String PUBLIC_KEY = "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();
}
}

3.3.4.3  Resource Services Licensing tests 
where we test Image search courses http: // localhost: 31200 / course / coursepic / list / 4028e58161bd3b380161bd3bcd2f0000
not carry a token request is given: 

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

请求时携带令牌: 
http header中添加 Authorization: Bearer 令牌
 

3.3.4.4 解决swagger-ui无法访问 
当课程管理加了授权之后再访问swagger-ui则报错:

 
修改授权配置类ResourceServerConfifigconfifigure方法: 
针对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();
}

注意: 
通过上边的配置虽然可以访问swagger-ui,但是无法进行单元测试,除非去掉认证的配置或在上边配置中添加所有 
请求均放行("/**")。 

发布了835 篇原创文章 · 获赞 152 · 访问量 14万+

Guess you like

Origin blog.csdn.net/qq_40208605/article/details/104207451