WeChat third-party login (java version)

1. Enter the WeChat open platform to get appid and appSecret.

2. Example class:

package com.xx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xx.common.util.IdGen;
import com.xx.model.User;
import com.xx.service.UserService;
import com.xx.shiro.SubjectUtils;
import com.xx.shiro.UsernamePasswordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Description: Third-party authorized login
 *
 * @author ssl
 * @create 2018/04/22 10:03
 */
@Controller
@RequestMapping("auth")
public class AuthLogin extends BasicController {
    @Value("${project.url}")
    private String projectUrl;
    @Value("${wechat.qrconnect.appid}")
    private String weChatAppid;
    @Value("${wechat.qrconnect.appSecret}")
    private String weChatAppSecret;
    @Value("${wechat.qrconnect.url}")
    private String weChatQrconnectUrl;
    @Value("${wechat.auth.url}")
    private String wechatAuthUrl;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserService userService;

    /**
     * WeChat login page
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "wechat")
    public String weChatLogin(HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/homepage";
        }
        String weChatState = IdGen.uuid();
        SubjectUtils.getSession().setAttribute("weChatState", weChatState);
        String callBackUrl = projectUrl + "/auth/wechat/callback";
        String url = weChatQrconnectUrl + "?appid=" + weChatAppid + "&redirect_uri=" + URLEncoder.encode(callBackUrl,
                "UTF-8") +
                "&response_type=code&scope=snsapi_login&state=" + weChatState + "#wechat_redirect";
        // response.sendRedirect(url);
        return "redirect:" + url;
    }

    @RequestMapping(value = "wechat/callback")
    public String callBackUrl(HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse
            response) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/homepage";
        }
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String openid = "";
        if (state.equals(SubjectUtils.getSession().getAttribute("weChatState"))) {
            if (StringUtils.isNotBlank(code)) {
                /** Get access_token and openid through code */
                String url = wechatAuthUrl + "?appid=" + weChatAppid + "&secret=" + weChatAppSecret + "&code=" + code
                        + "&grant_type=authorization_code";
                String responseStr = restTemplate.getForObject(url, String.class);
                if (StringUtils.isNotBlank(responseStr)) {
                    JSONObject json = JSON.parseObject(responseStr);
                    if (json.containsKey("openid")) {
                        openid = json.getString("openid");
                    }
                }
            }
        }
        /** According to openid */
        if (StringUtils.isNotBlank(openid)) {
            User user = userService.getByOpenId(openid);
            if (null == user) {
                return "redirect:/register/wechatBinding/index?openId="+openid;
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getAccount(), "", false,
                    request.getRemoteHost(), "wechat", "");
            SecurityUtils.getSubject().login(usernamePasswordToken);
            return "redirect:/login";
        }
        addMessage(redirectAttributes, "Connection failed, please try again");
        return "redirect:/login";
    }
}
3. Configuration information:
#WeChat open platform
wechat.qrconnect.appid=xxx
wechat.qrconnect.appSecret=xxxxx
wechat.qrconnect.url=https://open.weixin.qq.com/connect/qrconnect
wechat.auth.url=https://api.weixin.qq.com/sns/oauth2/access_token

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325784059&siteId=291194637