The rapid development of micro-channel public number (four) micro-letter web page authorization

The introduction of authorization

OAuth2 introduced the concept of

OAuth2.0 version is a continuation of the OAuth protocol, but does not forward compatible OAuth 2.0 (ie completely abolished OAuth1.0). OAuth 2.0 client focus on ease of developers. On behalf of the user or by the interaction between the approved organization resource owners and HTTP service providers, or on behalf of third-party applications allow users to gain access permissions.

More from Baidu Encyclopedia, namely OAuth by the Resourse Owner (resource owners), Client (client), as well Provider (ISP) composition, Provider consists of two parts Authorization Server (authentication server) and Resource Server (resource server).

Page letter of authorization is based on micro OAuth2.0 agreement. For example, when we want to modify the number of public user's basic information, the public must first obtain the number of user data in the micro-channel; or if the user needs to access the phone's photo album when you modify pictures. If, after a conventional manner, a user logs public number, number of third-party public will be free to obtain information from the micro-channel end user, or all the phone's data, which resulted in password disclosure of the risks when you do not want to use the public number We worry about data leakage, can only change the password.

Micro-letter web authorization process

It appears OAuth protocol in order to solve these problems. He will be replaced by user name and password authorization by way of token authorization, the third party application requests access to a resource, the resource owner (user) agree to post-authorization, again access the service provider (micro-channel official) the whereabouts of the authentication server application token (Token), after authentication server agreed to release the token (token), and third-party applications to retake the token (token) destination server resources (micro-channel official) to apply the resources you want, open the resources required for this application after validation by the resource server.

Specifically, web authorization process is divided into four steps:

  1. Guide the user to enter the authorization page consent, access code
  2. Authorized by the code page in exchange for access_token (the base support in different access_token)
  3. If desired, developers can refresh the page authorize access_token, avoiding expired
  4. Openid authorization through the pages access_token and get information about users (UnionID support mechanisms)

See specific description of public development document number -> micro-letter web page authorization

Development Readiness

First, the micro-channel web developer tools

Facilitates client-tone, Download: micro-channel web developer tools

Second, the configuration page account

Test micro-channel public platform -> Experience Interface Permissions -> Web Services -> Web accounts -> Web authorization to obtain information about users -> Change

Here the use of temporary or within the network through the domain name, if the need to develop a micro-channel payment functions, need to use real domain name.

Third, configure a static page

According to the development of the document returned json, intends to make a page for displaying user information

Static resource location: templates / person.html, user details to display the page

Development steps

User consent, access code

A, URL

According to the document format of the URL, page guide is authorized: open.weixin.qq.com/connect/oau...

note:

  1. Micro-channel link would be authorized to do regular check strong match, if the parameter order link is incorrect, authorized pages will not have access to normal;
  2. Callbacks redirect_uri, https link should be used to secure the authorization code;
  3. Scope of authorization page snsapi_userinfo, you can follow access_tokenand openidpulling the user information;
  4. If the user agrees authorization, the page will jump to redirect_uri / code = CODE & state = STATE?;
  5. Parameters, as shown below:

Second, add a page forward controller

Because the project used temporarily thymeleaf template, no direct access to project static resources, you need to configure redirection Controller. (In order to facilitate the jump, and the back page URL remains the same name)

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

    // 用于thymeleaf环境下,跳转到字符串相应的html页面
    @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 {
        // 显式授权,获得code
        if (code != null) {
            JSONObject accessTokenJson = WeChatUtil.getWebAccessToken(code);
            WXPayUtil.getLogger().info("获取网页授权的AccessToken凭据: "+accessTokenJson.toJSONString());
            String openid = accessTokenJson.getString(("openid"));
            request.getSession().setAttribute("openid", openid);
            WXPayUtil.getLogger().info("index openid={}"+openid);
            // 重定向到预下单页面
            response.sendRedirect("user"); // 回调的访问地址
        } else {
            StringBuffer url = RequestUtil.getRequestURL(request);
            WXPayUtil.getLogger().info("index 请求路径:{}"+url);
            String path = WeChatUtil.WEB_REDIRECT_URL.replace("APPID", WeChatConstants.APP_ID).replace("REDIRECT_URI", url).replace("SCOPE", "snsapi_userinfo");
            WXPayUtil.getLogger().info("index 重定向:{}"+path);
            // 重定向到授权获取code的页面
            response.sendRedirect(path);
        }
    }
}    
复制代码

Third, start the project, visit: chety.mynatapp.cc/api/v1/wech...

Fourth, according to the format of the URL, replace the relevant parameters. Access: micro-channel authorization page

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

Fifth, click [agreed], the page will automatically jump to the [/person.html]

In the redirected URL, you can see the code and the state (there is no set, so empty)

Description code: code access_token as exchange of notes, each user will be authorized to bring the code is not the same, code can only be used once, five minutes is not used to automatically expire

Authorized by the code page in exchange for access_token

A, URL

After obtaining the code, request the following links for the access_token: api.weixin.qq.com/sns/oauth2/...

As the number of public and secret acquired access_token security levels are very high, only to be saved on the server, the client is not allowed to pass. Subsequent refresh access_token, get user information and other steps by access_token, also must be initiated from the server.

Second, add a method to get the access_token

  • WeChatUtil
//获取网页授权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";


/**
 * 通过code换取网页授权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);
}
复制代码

Returning to the description

Refresh access_token (if needed)

Since access_token has a shorter period, when the access_token expires, you can use refresh_token refreshed, refresh_token valid for 30 days, after refresh_token failure, requiring users to re-authorize.

A, URL

After obtaining the second step refresh_token, request the following links for the access_token: api.weixin.qq.com/sns/oauth2/...

grant_type filled in as refresh_token

Second, the method of adding tools

// 获取网页授权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";

/**
 * 刷新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);
}
复制代码

Pulling the user information (as required scope snsapi_userinfo)

A, URL

http: GET (using the https protocol) api.weixin.qq.com/sns/userinf...

Second, the method of adding tools

/**
 * 获取用户信息
 * @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);
}
复制代码

Third, add Jump User interface information

/**
 * 网页授权获取用户信息
 * @param code
 * @return
 */
@RequestMapping("/user")
public String person(String code,ModelMap map){
    if(code!=null) {
        //通过code来换取access_token
        JSONObject result = WeChatUtil.getWebAccessToken(code);
        //通过access_token和openid拉取用户信息
        JSONObject userInfo = WeChatUtil.getUserInfo(result.getString("access_token"), result.getString("openid"));
        WXPayUtil.getLogger().info("用户信息为:{}"+ JSON.toJSONString(userInfo));
        //获取json对象中的键值对集合
        Set<Map.Entry<String, Object>> entries = userInfo.entrySet();
        for (Map.Entry<String, Object> entry : entries) {          
            map.addAttribute(entry.getKey(),entry.getValue());
        }
    }
    return "person";
}
复制代码

Here keys directly with the user information contains the default values ​​for the micro-channel return, person page also uses the default name.

Fourth, once again visit:

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

We can see, already has information on the micro-letter returned

Attachment: Inspection Authorization certificate (access_token) is valid

http: GET (using the https protocol) api.weixin.qq.com/sns/auth?ac...

Guess you like

Origin juejin.im/post/5d615021f265da03e5233ef1