Code cloud to achieve authorization

1. Prepare the environment

  • springbootBasic services
  • IDEAThe compiler
  • The browser

2. Authorize the login

2.1 the principle

Third party authorization login, in fact, the use of OAuth2 authentication technology, the authorization code into the permission authentication

Authorization code mode: A third-party application applies for an authorization code and uses the authorization code to obtain the token of the third-party service

2.2 process

3. Environment preparation

3.1 Creating third-party Applications

  1. Login code cloud, after entering the home page. Click on the image in the upper right corner to enter Settings

  1. Find third-party applications in the security management group

  1. My application is empty without being created. Click right test create Application to go to the form page

The home page and callbacks are on my side like this

  1. Once saved, one is generatedClient_idClient_secretThis will be used in the service invocation

After the preparation environment is complete, you can start to write code. The premise is that you need to create a basic SpringBoot service, if not, you can click download. This is based on a basic out-of-the-box service packaged by SpringBoot itself.

4. Code development

4.1 Create a constant class to store the magic values needed

There is a way to put these basic constants in application.yml and read them

/ * * *@ClassName MayunOauth
 * @Description TODO
 * @Author xiongchao
 * @Date 2021/4/9 10:49
 **/
public class MayunOauth {


    /** * Steps for third-party authorization * 1. Obtain the specified third-party authorization page using client_id and callback methods * 2. If the third-party page is successfully authorized, use the callback method to obtain the returned common code * 3. Exchange a successful login ticket token from a third-party service through code and callback * 4. Obtaining the basic information of the user through the ticket token of the third-party service returns to the front page */
    
    // Code cloud the corresponding client ID in my application
    public static final String clientId = "";
     // The code cloud corresponds to my application
    public static final String  secret = "";
    // Address of the configured callback interface
    public static final String callback ="http://localhost:8001/user/login/callback";
    // Jump to the authorization page of the code cloud
    public static final String mayunURI = "https://gitee.com/oauth/authorize?client_id=" + clientId + "&redirect_uri="+ callback+"&response_type=code";
       // Exchange his token credentials with the code cloud's code
    public static final String postToken = "https://gitee.com/oauth/token";
    // Obtain user information through token credentials of the code cloud service
    public static final String userInfo = "https://gitee.com/api/v5/user";
}

Copy the code

The object that holds the data returned by a third-party token is not required

@Data
public class Oauth {

    private String accessToken;

    private String tokenType;

    private Long expiresIn;

    private String refreshToken;

    private String scope;

    private String createdAt;
}
Copy the code

4.2 Interface for Redirecting Third-party Authorization Pages

Add a picture of the code cloud on the corresponding front-end page. Click the picture to jump to the authorization login page of the code cloud. The interface is shown as follows

@apiOperation (value = "jump code cloud third-party login ")
    @GetMapping("/login/oauth")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        log.info("Redirect third-party login authentication");
        try {
            response.sendRedirect(MayunOauth.mayunURI);
        } catch(IOException e) { e.printStackTrace(); log.error(e.getMessage()); }}Copy the code

4.2 After clicking authorization, the configured callback interface will be triggered, and other operations can be performed on the interface

    1. Get the specified third-party authorization page using client_id and the callback method
    1. If the third-party page is successfully authorized, use the callback method to obtain the returned common code
    1. Exchange a successful login ticket token from a third-party service through code and callback
    1. The basic user information obtained through the ticket token of the third-party service is returned to the front-end page

The callback interface is shown below

 @GetMapping("/login/callback")
    public Result login(@RequestParam(value = "code") String code ) {
        log.info("Authentication success returns code :{}" ,code);
        // Go back to the token information in the code cloud through the returned code
        String token  = userService.getToken(code);
        JSONObject parse = (JSONObject) JSONObject.parse(token);
        // The token is received through a pre-created object. If you feel troublesome, you can directly convert the token to map and then fetch the token
        Oauth oauth = JSONObject.toJavaObject(parse,Oauth.class);
        // Obtain user information by token
        Map<String,Object> res  = userService.getUserInfo(oauth.getAccessToken());

        return Result.success(res);
    }
Copy the code

The service layer


    String getToken(String code);

    Map<String,Object> getUserInfo(String accessToken);

Copy the code

Interface implementation class

    @Override
    public String getToken(String code) {
        // This parameter format is mandatory and can refer to the official API of the code cloud
        Map<String,Object> params = new HashMap<>();
        params.put("grant_type"."authorization_code");
        params.put("code",code);
        params.put("client_id",MayunOauth.clientId);
        params.put("redirect_uri",MayunOauth.callback);
        params.put("client_secret",MayunOauth.secret);
        String post = HttpUtil.post(MayunOauth.postToken, params);

        return post;
    }

    @Override
    public Map<String, Object> getUserInfo(String accessToken) {
        Map<String,Object> params = new HashMap<>();
        params.put("access_token",accessToken);
        String userInfo = HttpUtil.get(MayunOauth.userInfo, params);
        Map<String, Object> res  = (Map<String, Object>) JSONObject.parse(userInfo);
        return res;
    }

Copy the code

4.3 Maven coordinate addresses of related classes

  1. httpRemote invocation of the servicehutool
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.1</version>
        </dependency>
Copy the code
  1. JOSNObjectiscom.alibaba.fastjson
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
Copy the code

4.4 User Information Can be Returned after a successful callback (Perform operations based on personal service requirements)