12 user authentication and gateway integration
- All requests will pass through the service gateway. The service gateway exposes the service to the outside world, carries out unified user authentication at the gateway, and then the gateway sends them to the service;
-
Since you want to authenticate users in the gateway, the gateway needs to know which URLs to authenticate, so you need to make rules for URLs;
-
api interfaces are asynchronous requests. We use url rules for matching, such as / api/*/auth / *. All users who meet the rules need to be authenticated.
12.1 adjusting the service gateway module
Create a new filter package in the service gateway module and create the AuthGlobalFilter class
@Component public class AuthGlobalFilter implements GlobalFilter, Ordered { private AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getPath(); System.out.println("==="+path); //Internal service interface, external access is not allowed if(antPathMatcher.match("/**/inner/**", path)) { ServerHttpResponse response = exchange.getResponse(); return out(response, ResultCodeEnum.PERMISSION); } // Long userId = this.getUserId(request); //api Interface, asynchronous request, verification, user must log in if(antPathMatcher.match("/api/**/auth/**", path)) { Long userId = this.getUserId(request); if(StringUtils.isEmpty(userId)) { ServerHttpResponse response = exchange.getResponse(); return out(response, ResultCodeEnum.LOGIN_AUTH); } } return chain.filter(exchange); } @Override public int getOrder() { return 0; } /** * api Interface authentication failed, return data * @param response * @return */ private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) { Result result = Result.build(null, resultCodeEnum); byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bits); //Specify the code, otherwise Chinese garbled code will appear in the browser response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); return response.writeWith(Mono.just(buffer)); } /** * Get the current login user id * @param request * @return */ private Long getUserId(ServerHttpRequest request) { String token = ""; List<String> tokenList = request.getHeaders().get("token"); //The token is not empty. Get the token directly if(null != tokenList) { token = tokenList.get(0); } //If the token is empty, this value is returned directly if(!StringUtils.isEmpty(token)) { return JwtHelper.getUserId(token); } return null; } }
Utils / request JS
// http request interceptor service.interceptors.request.use( config => { //Determine whether the cookie has a token value if (cookie.get("token")) { //Put the token value into the cookie config.headers["token"] = cookie.get("token"); } return config; }, err => { return Promise.reject(err); } );
13 OAuth2 open authorization
OAuth2 mainly solves some specific problems,
- Open inter system authorization
- Single sign on problem
OAuth (open authorization) is an open standard, which only stipulates the solution and does not specify what to do. It allows users to authorize third-party mobile applications to access the information they store on other service providers without providing user names and passwords to third-party mobile applications or sharing all the contents of their data. About the usage of OAuth2: https://blog.csdn.net/finalheart/article/details/103102828 (author: finalheart),
https://blog.csdn.net/weixin_34080571/article/details/91715402 (Title: implementing oauth2 based on spring-security-oauth2 Author: JhonXie)
13.1 OAuth2 application scenario
- Authorized login of third-party applications: when accessing some third-party applications on apps or web pages, users will need to log in to another cooperation platform for a long time, such as authorized login of QQ, microblog and wechat.
- Native app authorization: app login requests the background interface. For security authentication, all requests carry token information. If login authentication and request background data.
- Front end and back end separated single page application (spa): front end and back end separated framework. The front end requests background data and needs oauth2 security authentication, such as apps developed using vue and react h5.
13.2 OAuth2 usage
In fact, oauth is a process. We write code according to the requirements of this process. The process is shown in the figure below:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-3xpiedlt-1640678445170) (C: \ users \ 1234 \ appdata \ roaming \ typora \ typora user images \ image-20211227193323755. PNG)]
A. After the user opens the client, the client requires the user to give authorization
B. The user agrees to grant authorization to the client
c. The client uses the authorization obtained in the previous step to apply for a token from the authentication server
d. After the authentication server authenticates the client, it confirms that there is no error and agrees to issue the token
e. The client uses a token to apply to the resource server to obtain resources
f. The resource server confirms that the token is correct and agrees to open the resource to the client
oauth has an authorization server. It is used as user authentication. For the server, it only needs to implement an oauth authorization server. For users (calling the R & D of authorization authentication), they only need to send a request according to the process.
13.3 four modes of oauth2
OAuth2 is designed not to expose passwords to third parties
1. authorization code is also the version with the highest security level. This is generally used to support refresh token. Microblog QQ login is this way.
2. password credentials supports refresh token, which has a low security level.
3. The simplified mode implicit does not support refresh token, which does not get the code.
4. The client mode client credentials does not support refresh token, which is used by trusted internal clients. Generally used between internal platforms