Github 第三方授權登錄教程
大致流程圖
1.首先註冊一個github帳號,Applications>Developer applications>Register a new application.
2.填入參數
Application name--應用名稱,隨意填
Homepage URL--如上圖可以填本地地址進行測試,127.0.0.1:port/xx/xx
Application description--應用描述,隨意填
Authorization callback URL--後端回調url,最重要的一環因爲github那邊回調會傳你一個code參數,下面會提到.提交申請
註冊之後會得到 github提供的client id和client secret有了這兩個東東就可以換取更多的信息了,不要交給壞人0.0
3.用戶點擊github登錄本地應用引導用戶跳轉到第三方授權頁 跳轉地址爲:
https://github.com/login/oauth/authorize?client_id=xxxxx&state=xxx&redirect_uri=xxxx;
(client_id 上面已經拿到了,state參數隨便傳多少,redirect_uri 就是你上面填的Authorization callback URL)
4.授權成功後會回調我們平臺,會重定向帶參數訪問我們上面的redirect_uri,後臺接收code這個參數,我們帶着這個code再次訪問github 地址:
https://github.com/login/oauth/access_token?client_id=xxx&client_secret=xxx&code=xxx&redirect_uri=http://127.0.0.1:8080/cqput-bbs/User/RegisteredByGithub.do
(這次會得到響應的access_token)
5.成功獲取access_token後就可以換取用戶信息了地址:
https://api.github.com/user?access_token=xxx;
(注意一下,這裏會有個坑,4,5步驟都儘量用get請求去訪問,第5步驟後端必須是模擬http get請求才能正確訪問拿到返回值,post 請求 直接報404)
6.得到github授權用戶的個人信息,就可以插入到我們的數據庫中去了,授權登錄成功,跳轉主頁
代碼:
/**
* 授權github用戶登錄
* @return
*/
@RequestMapping(value="RegisteredByGithub")//callback url
@ResponseBody
public JSONObject RegisteredByGithub(String code){
String me =CommonUtil.sendPost
("https://github.com/login/oauth/access_token?client_id="+ParamUtil.client_id+"&client_secret="+ParamUtil.client_secret+"&code="+code+"&redirect_uri=http://127.0.0.1:8080/cqput-bbs/User/RegisteredByGithub.do",null);
String atoke = me.split("&")[0];
String res = CommonUtil.sendGet("https://api.github.com/user?"+atoke+"");
JSONObject user = (JSONObject) JSON.parse(res);
return CommonUtil.constructResponse(1,"user_Person_Notice",user);
}
/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
InputStream instream = conn.getInputStream();
if(instream!=null){
in = new BufferedReader( new InputStreamReader(instream));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 發起http請求獲取返回結果
* @param req_url 請求地址
* @return
*/
public static String sendGet(String req_url) {
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(req_url);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 將返回的輸入流轉換成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
//res = new String(buffer.toString().getBytes("iso-8859-1"),"utf-8");
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}