[Third-party interconnection] 16. Wechat authorizes third-party login

A series of articles on third-party platforms, today finally started to update again, today continue to learn Wechat (wechat) authorized third-party login

1. Preparation

1. Apply for WeChat public test account

Since we are individual developers, we need to register and apply for a test account for WeChat public platform

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

Micro-channel public platform
After we log in with WeChat scan code, we can get appID and appsecret

Test number management

2. Follow the public test number

Test number QR code

3. Configure the callback domain name

Find "Web Account" in "Web Services" and modify the callback domain name of the "Web Authorization to Obtain User Basic Information" interface

Modify interface information
Authorization callback page domain name
Note: to say here is that the configuration web page callback authorized domain name , we usually docked with third-party interfaces are not the same, do not fill in the full address of a callback, but callback domain name, callback callback address under the domain name

  • For example :
    callback address: http://www.baidu.com/wechat/back
    then here: baidu.com

Novices are generally easy to confuse here. After the configuration is complete, click "Confirm".

2. Start development

1. Get application information

We will write the obtained appID and appsecret in the configuration file, my SpringBoot project here, I put it in the application.yml file

Configuration information

2. Introduce maven dependency

<!-- 网络请求 -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
<!-- alibaba的fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.51</version>
</dependency>

Here we need to use network requests, and the conversion of JSON objects, so I introduced httpclient and fastjson, and the rest of the dependencies, please introduce yourself

3. Get the "wechat" configuration information from the configuration file

/**
 * 公众平台提供的 appid 和 appsecret
 */
@Value("${wechat.oauth.appid}")
public String APPID;
@Value("${wechat.oauth.appsecret}")
public String APPKEY;
@Value("${wechat.oauth.callback}")
public String URL;

4. Redirect to the authorization page

/**
 * 请求授权页面
 */
@RequestMapping("/auth")
public String token(HttpSession session) throws Exception {
    
    
    // 用于第三方应用防止CSRF攻击
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    session.setAttribute("state", uuid);
	// Step1:获取Authorization Code
    String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
            "appid=" + APPID +
            "&redirect_uri=" + URLEncoder.encode(URL) +
            "&response_type=code" +
            "&scope=snsapi_userinfo" +
            "&state=" + uuid +
            "#wechat_redirect";
    return PasswordUtils.redirectTo(url);
}
  • Step1 parameters are explained as follows:
parameter Do you have to Description
appid Yes The unique identifier of the official account
redirect_uri Yes Callback link address redirected after authorization, please use urlEncode to process the link
response_type Yes Return type, please fill in code
scope Yes Application authorization scope, snsapi_base (do not pop up the authorization page, jump directly, only get the user openid), snsapi_userinfo (pop up the authorization page, you can get the nickname, gender, and location through openid. And, even if you are not concerned, As long as the user is authorized, the information can be obtained)
state no After redirection, the state parameter will be brought, and developers can fill in the parameter value of a-zA-Z0-9, up to 128 bytes
#wechat_redirect Yes Whether to open directly or do page 302 redirection, you must bring this parameter

Authorization page
At this time, when we visit, the authorization page will appear

5. Authorization callback

/**
 * 授权回调
 */
@GetMapping(value = "/callback")
public void callback(HttpServletRequest request) throws Exception {
    
    
    HttpSession session = request.getSession();
    // 得到Authorization Code
    String code = request.getParameter("code");
    // 我们放在地址中的状态码
    String state = request.getParameter("state");
    String uuid = (String) session.getAttribute("state");

    // 验证信息我们发送的状态码
    if (null != uuid) {
    
    
        // 状态码不正确,直接返回登录页面
        if (!uuid.equals(state)) {
    
    
            return PasswordUtils.redirectTo("/login");
        }
    }

    // Step2:通过Authorization Code获取Access Token
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=" + APPID +
            "&secret=" + APPKEY +
            "&code=" + code +
            "&grant_type=authorization_code";
    JSONObject resJson = HttpRequestUtils.httpRequestGet(url);
    if (null == resJson) {
    
    
        return PasswordUtils.redirectTo("/login");
    }
    String accessToken = resJson.getString("access_token");
    String openId = resJson.getString("openid");
    if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openId)) {
    
    
        return PasswordUtils.redirectTo("/login");
    }

    url = "https://api.weixin.qq.com/sns/userinfo?" +
            "access_token=" + accessToken +
            "&openid=" + openId +
            "&lang=zh_CN";
    // Step3: 获取微信用户信息
    resJson = HttpRequestUtils.httpRequestGet(url);
    /**
     * TODO 这时就该写自己的业务逻辑了
     */
}
  • Step2 parameters are explained as follows:
parameter Do you have to Description
appid Yes The unique identifier of the official account
secret Yes Appsecret of the official account
code Yes Fill in the code parameters obtained in the first step
grant_type Yes Fill in as authorization_code
  • Step3 parameters are explained as follows:
parameter Do you have to Description
access_token Yes Webpage authorization interface call credentials, note: this access_token is different from the basic supported access_token
openid Yes Unique ID of the user
lang Yes Return to the country and region language version, zh_CN simplified, zh_TW traditional, en English

6. Network request method

Step 2 and Step 3 are both GET request methods

/**
 * GET 请求
 */
public static JSONObject httpRequestGet(String url) throws IOException {
    
    
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
    
    
        String result = EntityUtils.toString(entity, "UTF-8");
        return JSONObject.parseObject(result);
    }
    httpGet.releaseConnection();
    return null;
}

3. Documentation

The document address for WeChat authorized login is as follows:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

Four, summary

The authorization authentication process conforms to the basic OAuth2 authentication process. For applications, the process consists of two steps: obtaining Authorization Code and obtaining Access Token through Authorization Code, as shown in the figure:

OAuth authorization authentication

If you find deficiencies in reading, please leave a message! ! !

Guess you like

Origin blog.csdn.net/qq_40065776/article/details/109369262