栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

OAuth2 gitee社区登录笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

OAuth2 gitee社区登录笔记

环境
  
        
            org.apache.httpcomponents
            httpcore
            4.4.12
        
        
            org.apache.httpcomponents
            httpclient
            4.5.13
            compile
        

 

package com.xc.common.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    
    public static HttpResponse doGet(String host, String path, String method,
                                     Map headers,
                                     Map querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        if (headers != null) {
            for (Map.Entry e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
        }


        return httpClient.execute(request);
    }

    
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      Map bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        if (headers != null) {
            for (Map.Entry e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
        }


        if (bodys != null) {
            List nameValuePairList = new ArrayList();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    
    public static HttpResponse doPut(String host, String path, String method,
                                     Map headers,
                                     Map querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    
    public static HttpResponse doPut(String host, String path, String method,
                                     Map headers,
                                     Map querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map headers,
                                        Map querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

package com.xc.common.exception;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
public class Assert {
    
    public static void notNull(Object obj, BizCodeEnume BizCodeEnume) {
        if (obj == null) {
//            log.info("obj is null...............................");
            System.out.println("obj is null...............................");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void isNull(Object object, BizCodeEnume BizCodeEnume) {
        if (object != null) {
//            log.info("obj is not null......");
            System.out.println("obj is not null......");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void isNullList(List list, BizCodeEnume BizCodeEnume) {
        if (CollectionUtils.isNotEmpty(list)) {
//            log.info("list is not null......");
            System.out.println("list is not null......");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void notEmptyList(List list, BizCodeEnume BizCodeEnume) {
        if (CollectionUtils.isEmpty(list)) {
//            log.info("list is null......");
            System.out.println("list is null......");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void isTrue(boolean expression, BizCodeEnume BizCodeEnume) {
        if (!expression) {
//            log.info("fail...............");
            System.out.println("fail...............");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void notEquals(Object m1, Object m2, BizCodeEnume BizCodeEnume) {
        if (m1.equals(m2)) {
//            log.info("equals...............");
            System.out.println("equals...............");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void equals(Object m1, Object m2, BizCodeEnume BizCodeEnume) {
        if (!m1.equals(m2)) {
//            log.info("not equals...............");
            System.out.println("not equals...............");
            throw new BusinessException(BizCodeEnume);
        }
    }

    
    public static void notEmpty(String s, BizCodeEnume BizCodeEnume) {
        if (StringUtils.isEmpty(s)) {
//            log.info("is empty...............");
            System.out.println("is empty...............");
            throw new BusinessException(BizCodeEnume);
        }
    }
}

 

后端实现

实体

private String socialUid;

private String accessToken;

private String expiresIn;
private String nickname;
//Controller
@PostMapping("/oauth2/gitee-login")
public R giteeLogin(@RequestParam("giteeInfo") String giteeInfo) throws Exception {
    MemberEntity member = memberService.giteeLogin(giteeInfo);
    return R.ok().setData(member);
}

//Service

MemberEntity giteeLogin(String giteeInfo) throws Exception;

//ServiceImpl

public MemberEntity giteeLogin(String giteeInfo) throws Exception {
    // 拿到accesstoken,获取用户基本信息
    JSONObject baseJson = JSON.parseObject(giteeInfo);
    Map params = new HashMap<>();
    String accessToken = baseJson.getString("access_token");
    String expiresIn = baseJson.getString("expires_in");
    params.put("access_token", accessToken);
    HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", null, params);

    Assert.isTrue(response.getStatusLine().getStatusCode() == 200, BizCodeEnume.OAUTH2_GITEE_EXCEPTION);

    String s = EntityUtils.toString(response.getEntity());
    JSONObject jsonObject = JSON.parseObject(s);
    String id = jsonObject.getString("id");

    MemberEntity member = this.getOne(new QueryWrapper().eq("social_uid", "gitee" + "_" + id));
    if (member != null) {
        // 说明已经注册过,更新令牌、令牌过期时间
        MemberEntity newMember = new MemberEntity();
        newMember.setId(member.getId());
        newMember.setAccessToken(accessToken);
        newMember.setExpiresIn(expiresIn);
        this.updateById(member);
        return member;
    } else {
        // 第一次登录,需要注册
        MemberEntity newMember = new MemberEntity();
        newMember.setSocialUid("gitee" + "_" + id);
        newMember.setNickname(jsonObject.getString("name"));//用户名字
        newMember.setAccessToken(accessToken);
        newMember.setExpiresIn(expiresIn);
        this.save(newMember);
        return newMember;
    }
}
 前端事件
               
  • gitee
  • 后端响应前端事件并保存用户数据
    package com.xc.gulimallauthserver.controller;
    
    import com.xc.common.utils.HttpUtils;
    import com.xc.common.utils.R;
    import com.xc.gulimallauthserver.feign.MemberFeignservice;
    import org.apache.http.HttpResponse;
    import org.apache.http.util.EntityUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import javax.annotation.Resource;
    import java.util.HashMap;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/web/oauth2")
    public class OAuth2Controller {
        @Resource
        private MemberFeignservice memberFeignService;
    
        
        @GetMapping("/gitee/success")
        public String gitee(@RequestParam("code") String code) throws Exception {
            // 准备请求参数
            Map params = new HashMap<>();
            params.put("client_id","11340ee43");//gitee申请第三方应用
            params.put("redirect_uri","http://xc.com/web/oauth2/gitee/success");
            params.put("client_secret","7ebef6");//gitee申请第三方应用
            params.put("code",code);
            params.put("grant_type","authorization_code");
    
            // 获取accesstoken
            HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, params);
    
            if (response.getStatusLine().getStatusCode() == 200) {
                // 说明获取到了
                // 取出返回数据
                String giteeInfo = EntityUtils.toString(response.getEntity());
                    // 我这里使用了远程调用,接口就是上面的giteeLogin
                 R r = memberFeignService.giteeLogin(giteeInfo);
                if (r.getCode() == 0) {
                    return "redirect:http://xc.com/";
                }
    
            }else{
                return "redirect:http://xc.com/login.html";
            }
            return "redirect:http://xc.com/login.html";
        }
    }
    
    gitee申请第三方应用  

     

    然后申请就好了 

     这里的redirect_uri路径要与前端事件以及OAuth2Controller里的redirect_uri保存一致

     

    暑期编程PK赛 得CSDN机械键盘等精美礼品!
    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/1016553.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号