孙军萍 發表於 2021-10-18 19:45:00

OAuth2.0整合gitee第三方登录注册

<h2 id="oauth20">OAuth2.0</h2>
<ul>
<li>
<p>OAuth: : OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容。</p>
</li>
<li>
<p>OAuth2.0 :对于用户相关的 OpenAPI(例如获取用户信息,动态同步,照片,日志,分享等),为了保护用户数据的安全和隐私,第三方网站访问用户数据前都需要显式的向用户征求授权</p>
</li>
</ul>
<p><strong>授权流程图示:</strong></p>
<p><img src="https://gitee.com/yanglingcong/picture/raw/master/202110142137236.png" alt="image-20211014213715104" loading="lazy"></p>
<p>其他第三方服务类似</p>
<h3 id="申请gitee第三方应用id和密钥">申请Gitee第三方应用ID和密钥</h3>
<p><img src="https://gitee.com/yanglingcong/picture/raw/master/202110151604427.png" alt="image-20211015160443305" loading="lazy"></p>
<h3 id="将信息保存至项目中">将信息保存至项目中</h3>
<pre><code class="language-yaml">gitee:
   oauth:
    clientid: XX
    clientsecret: XX
    callback: XX
</code></pre>
<p>项目导入依赖</p>
<pre><code class="language-xml">&lt;!-- 网络请求 --&gt;
&lt;dependency&gt;
        &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;
        &lt;artifactId&gt;httpclient&lt;/artifactId&gt;
        &lt;version&gt;4.5.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- alibaba的fastjson --&gt;
&lt;dependency&gt;
        &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
        &lt;artifactId&gt;fastjson&lt;/artifactId&gt;
        &lt;version&gt;1.2.51&lt;/version&gt;
&lt;/dependency&gt;

</code></pre>
<p>添加工具类<code>GiteeHttpClient</code></p>
<pre><code class="language-java">public class GiteeHttpClient {
    /**
   * 获取Access Token
   * post
   */
    public static JSONObject getAccessToken(String url) throws IOException {
      HttpClient client = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(url);
      httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
      HttpResponse response = client.execute(httpPost);
      HttpEntity entity = response.getEntity();
      if (null != entity) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return JSONObject.parseObject(result);
      }
      httpPost.releaseConnection();
      return null;
    }

    /**
   * 获取用户信息
   * get
   */
    public static JSONObject getUserInfo(String url) throws IOException {
      JSONObject jsonObject = null;
      CloseableHttpClient client = HttpClients.createDefault();

      HttpGet httpGet = new HttpGet(url);
      httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
      HttpResponse response = client.execute(httpGet);
      HttpEntity entity = response.getEntity();

      if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
      }

      httpGet.releaseConnection();

      return jsonObject;
    }

}
</code></pre>
<p>页面登陆按钮的请求方法</p>
<pre><code class="language-java">@Controller
public class GiteeController {
    /**
   * gitee授权中提供的 appid 和 appkey
   */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;

    /**
   * 请求授权页面
   */
    @GetMapping(value = "/gitee/auth")
    public String qqAuth(HttpSession session) {
      // 用于第三方应用防止CSRF攻击
      String uuid = UUID.randomUUID().toString().replaceAll("-", "");
      session.setAttribute("state", uuid);

      // Step1:获取Authorization Code
      String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&amp;client_id=" + CLIENTID +
                "&amp;redirect_uri=" + URLEncoder.encode(URL) +
                "&amp;state=" + uuid +
                "&amp;scope=user_info";

      //重定向
      return "redirect:"+url;
    }
}
</code></pre>
<p>点击同意授权后,编写<code>OAuth2Controller</code>控制器,里面添加回调方法</p>
<pre><code class="language-java">@Slf4j
@Controller
public class OAuth2Controller {
    /**
   * gitee授权中提供的 appid 和 appkey
   */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;


/**
* 授权回调
*/
@GetMapping(value = "/callback")
public String giteeCallback(HttpServletRequest request) throws Exception {
    HttpSession session = request.getSession();
    // 得到Authorization Code
    String code = request.getParameter("code");
    // 我们放在地址中的状态码
    String state = request.getParameter("state");
    String uuid = (String) session.getAttribute("state");

    // 验证信息我们发送的状态码
    if (null != uuid) {
      // 状态码不正确,直接返回登录页面
      if (!uuid.equals(state)) {
            return PasswordUtils.redirectTo("/login");
      }
    }

    // Step2:通过Authorization Code获取Access Token
    String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
            "&amp;client_id=" + CLIENTID +
            "&amp;client_secret=" + CLIENTSECRET +
            "&amp;code=" + code +
            "&amp;redirect_uri=" + URL;
    JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

    // Step3: 获取用户信息
    url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
    JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
    /**
   * 获取到用户信息之后,就该写你自己的业务逻辑了
   */
    return PasswordUtils.redirectTo("/success");
}

}
</code></pre><br><br>
来源:https://www.cnblogs.com/cg-ww/p/15422015.html
頁: [1]
查看完整版本: OAuth2.0整合gitee第三方登录注册