侧边栏壁纸
博主头像
qingtian博主等级

喜欢是一件细水流长的事,是永不疲惫的双向奔赴~!

  • 累计撰写 104 篇文章
  • 累计创建 48 个标签
  • 累计收到 1 条评论

微信扫描登录实现

qingtian
2020-07-12 / 0 评论 / 0 点赞 / 1,602 阅读 / 20,936 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-11-09,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

微信扫描登录实现

时序图

时序图

一、生成二维码页面

生成二维码的主要流程

流程

(1)添加配置

application.properties添加相关配置信息

# 微信开放平台 appid
wx.open.app_id=你的appid
# 微信开放平台 appsecret
wx.open.app_secret=你的appsecret
# 微信开放平台 重定向url
wx.open.redirect_url=http://你的服务器名称/api/ucenter/wx/callback

(2)创建常量类

ConstantPropertiesUtil
@Component
public class ConstantPropertiesUtil implements InitializingBean {


    @Value("${wx.open.app_id}")
    private String appId;

    @Value("${wx.open.app_secret}")
    private String appSecret;

    @Value("${wx.open.redirect_url}")
    private String redirectUrl;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;



    @Override
    public void afterPropertiesSet() throws Exception {

        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

(3)创建Controller

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApicontroller {


    @Autowired
    private MemberService memberService;

    /**
     * 生成二维码
     */
    @GetMapping("/login")
    public String genQrConnect() {

        //请求微信提供的固定地址,向地址中拼接参数,生成二维码
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        try {
            //对重定向的地址使用Encode编码
            String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");



            String state = "atguan";//使用内网穿透的前置域名,仅仅是在个人测试使用

            //在baseurl中拼接参数
            String qrcodeUrl = String.format(
                    baseUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    redirectUrl,
                    state
            );

            return "redirect:"+qrcodeUrl;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }

}

启动项目,访问网址可以看到二维码页面

二维码

根据时序图已经完成

1

二、获得用户的code(临时票据)

(1)在Controller中加入回调方法

@GetMapping("callback")
public String callback(String code, String state, HttpSession session) {

    //得到授权临时票据code
    System.out.println("code = " + code);
    System.out.println("state = " + state);
}

测试回调方法是否可用

//返回的code
0618nIko0Udctm14zijo0OFQko08nIki

三、通过code加上appid和appsecret换取access_token

(1)加入依赖

<!--httpclient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
<!--commons-io-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<!--gson-->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

(2)创建httpClient工具类

public class HttpClientUtils {

   public static final int connTimeout=10000;
   public static final int readTimeout=10000;
   public static final String charset="UTF-8";
   private static HttpClient client = null;

   static {
      PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
      cm.setMaxTotal(128);
      cm.setDefaultMaxPerRoute(128);
      client = HttpClients.custom().setConnectionManager(cm).build();
   }

   public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
      return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
   }

   public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
      return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
   }

   public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
         SocketTimeoutException, Exception {
      return postForm(url, params, null, connTimeout, readTimeout);
   }

   public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
         SocketTimeoutException, Exception {
      return postForm(url, params, null, connTimeout, readTimeout);
   }

   public static String get(String url) throws Exception {
      return get(url, charset, null, null);
   }

   public static String get(String url, String charset) throws Exception {
      return get(url, charset, connTimeout, readTimeout);
   }

   /**
    * 发送一个 Post 请求, 使用指定的字符集编码.
    *
    * @param url
    * @param body RequestBody
    * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
    * @param charset 编码
    * @param connTimeout 建立链接超时时间,毫秒.
    * @param readTimeout 响应超时时间,毫秒.
    * @return ResponseBody, 使用指定的字符集编码.
    * @throws ConnectTimeoutException 建立链接超时异常
    * @throws SocketTimeoutException  响应超时
    * @throws Exception
    */
   public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
         throws ConnectTimeoutException, SocketTimeoutException, Exception {
      HttpClient client = null;
      HttpPost post = new HttpPost(url);
      String result = "";
      try {
         if (StringUtils.isNotBlank(body)) {
            HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
            post.setEntity(entity);
         }
         // 设置参数
         Builder customReqConf = RequestConfig.custom();
         if (connTimeout != null) {
            customReqConf.setConnectTimeout(connTimeout);
         }
         if (readTimeout != null) {
            customReqConf.setSocketTimeout(readTimeout);
         }
         post.setConfig(customReqConf.build());

         HttpResponse res;
         if (url.startsWith("https")) {
            // 执行 Https 请求.
            client = createSSLInsecureClient();
            res = client.execute(post);
         } else {
            // 执行 Http 请求.
            client = HttpClientUtils.client;
            res = client.execute(post);
         }
         result = IOUtils.toString(res.getEntity().getContent(), charset);
      } finally {
         post.releaseConnection();
         if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
            ((CloseableHttpClient) client).close();
         }
      }
      return result;
   }


   /**
    * 提交form表单
    *
    * @param url
    * @param params
    * @param connTimeout
    * @param readTimeout
    * @return
    * @throws ConnectTimeoutException
    * @throws SocketTimeoutException
    * @throws Exception
    */
   public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
         SocketTimeoutException, Exception {

      HttpClient client = null;
      HttpPost post = new HttpPost(url);
      try {
         if (params != null && !params.isEmpty()) {
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
               formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
            post.setEntity(entity);
         }

         if (headers != null && !headers.isEmpty()) {
            for (Entry<String, String> entry : headers.entrySet()) {
               post.addHeader(entry.getKey(), entry.getValue());
            }
         }
         // 设置参数
         Builder customReqConf = RequestConfig.custom();
         if (connTimeout != null) {
            customReqConf.setConnectTimeout(connTimeout);
         }
         if (readTimeout != null) {
            customReqConf.setSocketTimeout(readTimeout);
         }
         post.setConfig(customReqConf.build());
         HttpResponse res = null;
         if (url.startsWith("https")) {
            // 执行 Https 请求.
            client = createSSLInsecureClient();
            res = client.execute(post);
         } else {
            // 执行 Http 请求.
            client = HttpClientUtils.client;
            res = client.execute(post);
         }
         return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
      } finally {
         post.releaseConnection();
         if (url.startsWith("https") && client != null
               && client instanceof CloseableHttpClient) {
            ((CloseableHttpClient) client).close();
         }
      }
   }




   /**
    * 发送一个 GET 请求
    *
    * @param url
    * @param charset
    * @param connTimeout  建立链接超时时间,毫秒.
    * @param readTimeout  响应超时时间,毫秒.
    * @return
    * @throws ConnectTimeoutException   建立链接超时
    * @throws SocketTimeoutException   响应超时
    * @throws Exception
    */
   public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
         throws ConnectTimeoutException,SocketTimeoutException, Exception {

      HttpClient client = null;
      HttpGet get = new HttpGet(url);
      String result = "";
      try {
         // 设置参数
         Builder customReqConf = RequestConfig.custom();
         if (connTimeout != null) {
            customReqConf.setConnectTimeout(connTimeout);
         }
         if (readTimeout != null) {
            customReqConf.setSocketTimeout(readTimeout);
         }
         get.setConfig(customReqConf.build());

         HttpResponse res = null;

         if (url.startsWith("https")) {
            // 执行 Https 请求.
            client = createSSLInsecureClient();
            res = client.execute(get);
         } else {
            // 执行 Http 请求.
            client = HttpClientUtils.client;
            res = client.execute(get);
         }

         result = IOUtils.toString(res.getEntity().getContent(), charset);
      } finally {
         get.releaseConnection();
         if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
            ((CloseableHttpClient) client).close();
         }
      }
      return result;
   }


   /**
    * 从 response 里获取 charset
    *
    * @param ressponse
    * @return
    */
   @SuppressWarnings("unused")
   private static String getCharsetFromResponse(HttpResponse ressponse) {
      // Content-Type:text/html; charset=GBK
      if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
         String contentType = ressponse.getEntity().getContentType().getValue();
         if (contentType.contains("charset=")) {
            return contentType.substring(contentType.indexOf("charset=") + 8);
         }
      }
      return null;
   }



   /**
    * 创建 SSL连接
    * @return
    * @throws GeneralSecurityException
    */
   private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
      try {
         SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
               return true;
            }
         }).build();

         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
               return true;
            }

            @Override
            public void verify(String host, SSLSocket ssl)
                  throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert)
                  throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns,
                           String[] subjectAlts) throws SSLException {
            }

         });

         return HttpClients.custom().setSSLSocketFactory(sslsf).build();

      } catch (GeneralSecurityException e) {
         throw e;
      }
   }

   public static void main(String[] args) {
      try {
         String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
         //String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
            /*Map<String,String> map = new HashMap<String,String>();
            map.put("name", "111");
            map.put("page", "222");
            String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/
         System.out.println(str);
      } catch (ConnectTimeoutException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (SocketTimeoutException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

}

(3)在Controller中的callback方法中添加

//返回临时票据code

//拿着code请求微信的固定地址
String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
        "?appid=%s" +
        "&secret=%s" +
        "&code=%s" +
        "&grant_type=authorization_code";

//设置其中的参数
baseAccessTokenUrl = String.format(
        baseAccessTokenUrl,
        ConstantPropertiesUtil.WX_OPEN_APP_ID,
        ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
        code
);
try {
            //使用httpclient发送请求,获取openid和access_token
            String resultAccessToken = HttpClientUtils.get(baseAccessTokenUrl);

            System.err.println(resultAccessToken);

            //将返回的字符串转化为map对象
            Gson gson = new Gson();
            Map<String,Object> map = gson.fromJson(resultAccessToken, HashMap.class);

            //获取凭证和id
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");

        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

此时已经获取到用户的openid以及access_token

其中得到的resultAccessToken为

{
"access_token": "35_V_frEupCU8nXXdTHVjX1rFZois8ph6WrSqtTFQ6u_f-J-JYJvjpDwLPjwULgXhUNe_IgCgH4lmFq9L6ucuZAJ-fbRy64v7WgWIhJlCUihg0",
"expires_in": 7200,
"refresh_token": "35_3De8UjudLa6GmHexFPu4ZpK2Vj5l6eJfXJWC9OyFfYaTWe9XwpBA4dJj9N9xzkQamYmHcpJCspeWoB5wVadpec03HJlPzYdlzRPzx_goEwA",
"openid": "o3_SC5-FiweooMVZNwNPsFwT5JS0",
"scope": "snsapi_login",
"unionid": "oWgGz1E6yQhKUIGSLzRUetlKLLzw"
}

再次参考时序图已经完成

2

四、获取用户信息

流程

(1)通过openid以及access_token可以请求微信的地址

完善callback方法

			Member member = memberService.getOpenUserInfo(openid);

            //如果为空,用户不存在,注册
            if (member == null) {

            //访问微信的资源服务器,获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                baseUserInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );

                String resultUserInfo = HttpClientUtils.get(baseUserInfoUrl);

                System.err.println(resultUserInfo);

                Map<String,Object> userMap = gson.fromJson(resultUserInfo,HashMap.class);

                //得到用户的nickname
                String nickname =(String) userMap.get("nickname");

                //得到用户的头像
                String headimgurl = (String) userMap.get("headimgurl");



                //添加
                Member member1 = new Member();
                member1.setNickname(nickname);
                member1.setAvatar(headimgurl);
                member1.setOpenid(openid);

                memberService.save(member1);
            }

业务实现:MemberServiceImpl.java

@Override
public Member getOpenUserInfo(String openid) {

    QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("openid", openid);

    Member member = baseMapper.selectOne(queryWrapper);
    return member;
}

五、使用JWT进行跨域身份验证

(1)加入jwt工具依赖

<!-- JWT -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.7.0</version>
</dependency>

(2)创建JWT工具类

public class JwtUtils {


    public static final String SUBJECT = "guli";

    //秘钥
    public static final String APPSECRET = "guli";

    //生成jwt字符串的过期时间,毫秒,30分钟
    public static final long EXPIRE = 1000 * 60 * 30;


    /**
     * 生成jwt token
     *
     * @param member
     * @return
     */
    public static String geneJsonWebToken(Member member) {

        if (member == null || StringUtils.isEmpty(member.getId())
                || StringUtils.isEmpty(member.getNickname())
                || StringUtils.isEmpty(member.getAvatar())) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", member.getId())
                .claim("nickname", member.getNickname())
                .claim("avatar", member.getAvatar())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }


    /**
     * 校验jwt token
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        Claims claims = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();
        return claims;
    }

    //测试生成jwt token
    private static String testGeneJwt(){
        Member member = new Member();
        member.setId("999");
        member.setAvatar("www.guli.com");
        member.setNickname("Helen");

        String token = JwtUtils.geneJsonWebToken(member);
        System.out.println(token);
        return token;
    }

    //测试校验jwt token
    private static void testCheck(String token){

        Claims claims = JwtUtils.checkJWT(token);
        String nickname = (String)claims.get("nickname");
        String avatar = (String)claims.get("avatar");
        String id = (String)claims.get("id");
        System.out.println(nickname);
        System.out.println(avatar);
        System.out.println(id);
    }


    //测试用例
    public static void main(String[] args){

        Member member = new Member();
        member.setId("11");
        member.setNickname("lucy");

        member.setAvatar("abcd");


        String token = geneJsonWebToken(member);

        System.err.println(token);

        Claims claims = checkJWT(token);
        String id = (String) claims.get("id");
        String nickname = (String) claims.get("nickname");
        String avatar = (String) claims.get("avatar");

        System.err.println(id);
        System.err.println(nickname);
        System.err.println(avatar);
    }
}

(3)继续完善callback方法

if (member == null) {

    //访问微信的资源服务器,获取用户信息
        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";

        baseUserInfoUrl = String.format(
                baseUserInfoUrl,
                access_token,
                openid
        );

        String resultUserInfo = HttpClientUtils.get(baseUserInfoUrl);

        System.err.println(resultUserInfo);

        Map<String,Object> userMap = gson.fromJson(resultUserInfo,HashMap.class);

        String nickname =(String) userMap.get("nickname");

        String headimgurl = (String) userMap.get("headimgurl");



        //添加
        Member member1 = new Member();
        member1.setNickname(nickname);
        member1.setAvatar(headimgurl);
        member1.setOpenid(openid);

        memberService.save(member1);
    }

    //根据member生成jwt字符串
    String token = JwtUtils.geneJsonWebToken(member);


    //回到首页面
    return "redirect:http://localhost:3000?token="+token;

} catch (Exception e) {
    e.printStackTrace();
    return null;

}

(4)根据token获得用户信息

/**
     * 根据token值获取用户信息
     */
    @PostMapping("/getUserInfoToken/{token}")
    public Result getUserInfoToken(@PathVariable("token") String token) {

        Claims claims = JwtUtils.checkJWT(token);

        String id = (String) claims.get("id");
        String nickname = (String) claims.get("nickname");
        String avatar = (String) claims.get("avatar");

        Member member = new Member();
        member.setAvatar(avatar);
        member.setNickname(nickname);
        member.setId(id);

        return Result.ok().data("member",member);
    }
0

评论区