您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么用Java代碼實現第三方驗證登錄”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么用Java代碼實現第三方驗證登錄”吧!
很多同學不太了解什么是應用回調地址webhooks(第三方登錄成功后,會返回到你指定的地址,并且攜帶驗證是否成功的參數信息)
clientId和client Sercret的主要作用是通過拼接得到請求地址,將地址重定向至授權登錄頁面
準備過程已完成
<!--servlet服務-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!--第三方登錄插件包-->
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
<version>1.3.2</version>
</dependency>
<!--服務器發送get,post工具包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
.clientId(CLIENT_ID) //Client ID
.clientSecret(CLIENT_SECRET) //Client Secret
.redirectUri(REDIRECTURI) //回調地址
.build());
String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
//跳轉到授權頁面
response.sendRedirect(authorizeUrl);
//http://localhost:8080/login?actionName=giteeCode&code=e063730161cd40cf&state=25c74eba2ac5f
String code = request.getParameter("code");
補充一個小小的坑,碼云第三方驗證需要加上header信息,否則會報403錯誤
String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;
Map<String,String> map = new HashMap<>();
map.put("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)");
JSONObject s = HttpUtils.post(url,map);
授權登錄失敗會返回message錯誤信息,標識登錄失敗
成功:
{ "access_token":"e386e20327b7c4", "refresh_token":"057c79c2d1f957a5cb4d", "scope":"user_info", "created_at":15488, "token_type":"bearer", "expires_in":86400 }
通過授權碼獲取到的json數據,其中access_token參數,可以訪問碼云的用戶數據
//https://gitee.com/api/v5/user?access_token=*******
String access_token = s.getString("access_token");
String url2 = "https://gitee.com/api/v5/user?access_token="+access_token;
JSONObject user = HttpUtils.get(url2,map);
//1、設置響應類型輸出流
response.setContentType("application/json;charset=UTF-8");
//2、將json轉為字符串
String str = JSON.toJSONString(user);
//3、得到字符輸出流
response.getWriter().write(str);
源碼:
在這小編要說一下回調地址操作1和回調地址操作2的區別
操作1:小編使用的是服務器的get,post發送請求,而跳轉“授權頁面”(giteeLogin 方法)使用的是插件,各位看主大大也可手動改為get請求,跳轉第三方登錄頁面,具體get地址請參考
碼云oauth文檔
其中A和B步驟,修改后就可以不用插件代碼跳轉授權頁面
操作2:完全使用的是JustAuth插件實現第三方登錄
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shsxt.utils.HttpUtils;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//ac85a173bb89ee
private final String CLIENT_ID = “Client ID”
private final String CLIENT_SECRET= “Client Secret”
private final String REDIRECTURI = “回調地址”
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取用戶行為
String actionName = request.getParameter("actionName");
//判斷用戶行為
if("giteeLogin".equals(actionName)) {
//如果發送碼云授權驗證
giteeLogin(request,response);
}else if("giteeCode".equals(actionName)) {
//giteeCode(request,response);
giteeCode2(request,response);
}
System.out.println("點擊了");
}
/**
* 回調地址后的操作1
* @param request
* @param response
*/
private void giteeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//獲取code
String code = request.getParameter("code");
String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;
Map<String,String> map = new HashMap<>();
map.put("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)");
JSONObject s = HttpUtils.post(url,map);
System.out.println(s);
//https://gitee.com/api/v5/user?access_token=*******
String access_token = s.getString("access_token");
String url2 = "https://gitee.com/api/v5/user?access_token="+access_token;
JSONObject user = HttpUtils.get(url2,map);
//1、設置響應類型輸出流
response.setContentType("application/json;charset=UTF-8");
//2、將json轉為字符串
String str = JSON.toJSONString(user);
//3、得到字符輸出流
response.getWriter().write(str);
}
/**
* 回調地址后的操作2
* @param request
* @param response
*/
private void giteeCode2(HttpServletRequest request, HttpServletResponse response) throws IOException {
String code = request.getParameter("code");
AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
.clientId(CLIENT_ID) //Client ID
.clientSecret(CLIENT_SECRET) //Client Secret
.redirectUri(REDIRECTURI) //回調地址
.build());
AuthResponse json = authRequest.login(code);
System.out.println(json);
}
/**
* 跳轉授權頁面
* @param request
* @param response
*/
private void giteeLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
//跳轉授權頁面
AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
.clientId(CLIENT_ID) //Client ID
.clientSecret(CLIENT_SECRET) //Client Secret
.redirectUri(REDIRECTURI) //回調地址
.build());
String authorizeUrl = authRequest.authorize();
//跳轉到授權頁面
response.sendRedirect(authorizeUrl);
}
}
服務器發送get/post請求工具類
package com.shsxt.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;
public class HttpUtils {
/*
*發送簡單post請求
*/
public static JSONObject post(String url) {
HttpPost post = new HttpPost(url);
return getResult(post);
}
/*
*發送帶Header的post請求
*/
public static JSONObject post(String url, Map<String, String> map) {
HttpPost post = new HttpPost(url);
if (!map.isEmpty()) {
Set<Map.Entry<String, String>> entrys = map.entrySet();
for (Map.Entry<String, String> entry : entrys) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
return getResult(post);
}
/*
*發送帶Header的get請求
*/
public static JSONObject get(String url, Map<String, String> map) {
HttpGet get = new HttpGet(url);
if (!map.isEmpty()) {
Set<Map.Entry<String, String>> entrys = map.entrySet();
for (Map.Entry<String, String> entry : entrys) {
get.setHeader(entry.getKey(), entry.getValue());
}
}
return getResult(get);
}
/*
*發送簡單的get請求
*/
public static JSONObject get(String url) {
HttpGet get = new HttpGet(url);
return getResult(get);
}
/*
*發送請求方法,請求響應為JSONObject
*/
private static JSONObject getResult(HttpRequestBase requestBase) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = null;
try {
result = EntityUtils.toString(httpClient.execute(requestBase).getEntity());
result = new String(result.getBytes("ISO-8859-1"),"utf-8");
httpClient.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
return new JSONObject(JSON.parseObject(result));
}
}
/*
*當請求響應為String時
*/
public static String getString(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
String result = null;
try {
result = EntityUtils.toString(httpClient.execute(get).getEntity());
httpClient.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
return result;
}
}
}
```*當請求響應為String時
*/
public static String getString(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
String result = null;
try {
result = EntityUtils.toString(httpClient.execute(get).getEntity());
httpClient.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
return result;
}
}
}
到此,相信大家對“怎么用Java代碼實現第三方驗證登錄”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。