Introduction of authorization

OAuth2 concept introduced

OAuth2.0 is a continuation of the OAuth protocol, but is not forward compatible with OAuth2.0 (i.e. completely repealing OAuth1.0). OAuth 2.0 focuses on simplicity for client developers. Either the user is represented by organizing an approved interaction between the resource owner and the HTTP server, or third-party applications are allowed to gain access on the user’s behalf.

OAuth is composed of Resourse Owner, Client, and Provider. A Provider consists of the Authorization Server and Resource Server.

Wechat web page authorization is based on OAuth2.0 protocol. For example, when we want to modify the basic information of users in the public account, the public account must first obtain user data in wechat; Or the user may need to access the phone’s album to modify an image. If according to the traditional way, after the user login public account, the third party public account can be free from the wechat end to obtain user information, or all the data of the phone, which has caused the hidden danger of password leakage, when you do not want to use the public account and worry about data leakage, can only change the password.

Wechat web page authorization process

The OAuth protocol is designed to solve these problems. He changed the authentication method of user name and password to Token authorization. After the third-party application requests to access the resource, the resource owner (user) agrees to the authorization, and then accesses the service provider (wechat official) to apply for the Token from the authentication server. After the authentication server agrees, the Token is issued. Then the third-party application takes the Token to the resource server (wechat official) to apply for the desired resources. The resource server will open the resources required by the application after the authentication.

Specifically, the web licensing process is divided into four steps:

  1. Guide the user to the authorization page to agree to the authorization and obtain the code
  2. Exchange web page authorization Access_token with code (different from the Access_token in basic support)
  3. If needed, developers can refresh the web page to authorize access_token and avoid expiration
  4. Obtain basic user information through web page authorization access_token and OpenID (support UnionID mechanism)

For specific introduction, see the official account development document -> wechat web page authorization

The development of preparation

1. Wechat Web developer tools

Easy in the client mode, download address: wechat Web developer tool

2. Configure web page accounts

Wechat test public platform -> experience interface permissions -> Web services -> Web account -> Web authorization to obtain basic user information -> modify

For the time being, the domain name of Intranet penetration is still used here. If you need to develop the wechat payment function, you need to use the real domain name.

Configure the static page

Based on the json returned from the development document, I plan to create a page that displays the user’s information

Static resource location: templates/person.html, which displays user details

Development steps

The user agrees to the authorization and obtains the code

A, URL

According to the documents, and guide web page authorization URL format for: open.weixin.qq.com/connect/oau…

Note:

  1. Wechat will do regular strong match check on the authorization link. If the parameter order of the link is wrong, the authorization page will not be able to access normally.
  2. The callbackredirect_uri, HTTPS links should be used to secure the authorization code;
  3. The page authorization scope issnsapi_userinfo“And then you can go throughaccess_tokenandopenidPull user information;
  4. If the user agrees to authorization, the page will redirect to redirect_uri/? Code = CODE&state = STATE;
  5. Parameter description:

Add the controller for forwarding the page

Because this item is temporarily used whenthymeleafTemplate, cannot directly access the static resources in the project, so you need to configure the redirected Controller. (For the convenience of jumping, the following page and THE URL to keep the same name)

  • IndexController:
@Controller
@RequestMapping("/api/v1/wechat1")
public class IndexController {

    // For the thymeleaf environment, jump to the HTML page corresponding to the string
    @RequestMapping("/{path}")
    public String webPath(@PathVariable String path) {
        return path;
    }

    @RequestMapping("/index")
    public void index(String code, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Give explicit authorization to get code
        if(code ! =null) {
            JSONObject accessTokenJson = WeChatUtil.getWebAccessToken(code);
            WXPayUtil.getLogger().info("Access the AccessToken credentials for web page authorization:"+accessTokenJson.toJSONString());
            String openid = accessTokenJson.getString(("openid"));
            request.getSession().setAttribute("openid", openid);
            WXPayUtil.getLogger().info("index openid={}"+openid);
            // Redirect to the pre-order page
            response.sendRedirect("user"); // Callback access address
        } else {
            StringBuffer url = RequestUtil.getRequestURL(request);
            WXPayUtil.getLogger().info("Index request path: {}"+url);
            String path = WeChatUtil.WEB_REDIRECT_URL.replace("APPID", WeChatConstants.APP_ID).replace("REDIRECT_URI", url).replace("SCOPE"."snsapi_userinfo");
            WXPayUtil.getLogger().info("Index redirection: {}"+path);
            // Redirect to the page where you are authorized to get the coderesponse.sendRedirect(path); }}}Copy the code

Third, start the project, access: chety mynatapp. Cc/API/v1 / wech…

4. Replace related parameters according to the URL format. Visit: wechat Authorization page

Open.weixin.qq.com/connect/oau…

5. After clicking “Agree”, the page will automatically jump to “/person.html”

In the redirected URL, you can see code and state(not set here, so empty)

Code description: The code is used as the ticket to exchange for the Access_token. The code attached to each user’s authorization is different. The code can be used only once and automatically expires if not used within 5 minutes

Exchange web page authorization Access_token through code

A, URL

Request access code, the following links for access_token: api.weixin.qq.com/sns/oauth2/…

Because the security level of secret and access_token obtained by the public account is very high, they must only be stored on the server and cannot be transmitted to the client. Subsequent steps such as refreshing the access_token and obtaining user information through the access_token must also be initiated from the server.

2. Add a method for obtaining the access_token

  • WeChatUtil
// Get the interface of the page authorization accessToken
public static final String GET_WEB_ACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";


/** * Use code to exchange access_token *@param code
 * @return* /
public static JSONObject getWebAccessToken(String code){
    String result = HttpUtil.get(GET_WEB_ACCESSTOKEN_URL.replace("APPID", WeChatConstants.APP_ID).replace("SECRET", WeChatConstants.APPSECRET).replace("CODE", code));
    return JSONObject.parseObject(result);
}
Copy the code

Return instructions

Refresh access_token (if required)

When access_token times out, refresh_token can be used to refresh. The validity period of refresh_token is 30 days. When refresh_token expires, the user needs to re-authorize it.

A, URL

For the second step after refresh_token, request the following links for access_token: api.weixin.qq.com/sns/oauth2/…

Grant_type: refresh_token

Add a tool class method

// Get the interface of the page authorization accessToken
public static final String GET_WEB_ACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

/** * Refresh access_token *@param refresh_token
 * @return* /
public static JSONObject refreshWebAccessToken(String refresh_token){
    String result = HttpUtil.get(GET_WEB_ACCESSTOKEN_URL.replace("APPID", WeChatConstants.APP_ID).replace("REFRESH_TOKEN", refresh_token));
    return JSONObject.parseObject(result);
}
Copy the code

Pull user information (scope snsapi_userInfo)

A, URL

HTTP: GET (please use the HTTPS protocol) api.weixin.qq.com/sns/userinf…

Add a tool class method

/** * Obtain user information *@param accessToken
 * @param openId
 * @return* /
public static JSONObject getUserInfo(String accessToken,String openId){
    String result = HttpUtil.get(GET_USERINFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openId));
    return JSONObject.parseObject(result);
}
Copy the code

3. Add an interface for forwarding user information

/** * Web page authorizes access to user information *@param code
 * @return* /
@RequestMapping("/user")
public String person(String code,ModelMap map){
    if(code! =null) {
        // Exchange access_token through code
        JSONObject result = WeChatUtil.getWebAccessToken(code);
        // Use access_token and OpenID to pull user information
        JSONObject userInfo = WeChatUtil.getUserInfo(result.getString("access_token"), result.getString("openid"));
        WXPayUtil.getLogger().info("User information: {}"+ JSON.toJSONString(userInfo));
        // Get the collection of key and value pairs in the JSON object
        Set<Map.Entry<String, Object>> entries = userInfo.entrySet();
        for(Map.Entry<String, Object> entry : entries) { map.addAttribute(entry.getKey(),entry.getValue()); }}return "person";
}
Copy the code

The key name that contains the user information is directly the default value returned by wechat, which is also used on the Person page.

Iv. Re-visit:

Open.weixin.qq.com/connect/oau…

As you can see, the message returned in wechat has been obtained

Attached: Verify the validity of the access_token

HTTP: GET (please use the HTTPS protocol) api.weixin.qq.com/sns/auth?ac…