社會化登錄之豆瓣小結
1:登錄豆瓣網,註冊一個開發者賬號,然後選擇我的應用。
2:創建我的應用:
回調地址很重要,要和自己請求時的回調地址一致。QQ對於回調地址只是匹配域名,其他幾個是直接匹配整個地址,然後加上參數code進行回調。
3: 查看和配置應用基本信息:
可以看到:
下面的要注意嘍:
豆瓣測試自己的賬號的時候必須把自己添加進去,其他社會化登錄不要添加自己賬號。
4:實現流程參考:http://douban-oauth2.wikispaces.com/
基本使用:
頁面鏈接:<a href="https://www.douban.com/service/auth2/auth?client_id=0e3bfd6c9e1edf942ab3f845da5c9ebc&response_type=code&redirect_uri=${appContext}sociallogin/dologin?SocialLoginParams=DouBan"></a>
說明:通過該鏈接,返回code
調用實現:
------------------------------------基本調用----------------------------------------
String code = paramsMapx.getString("code");//code在回調方法中,是通過上面的頁面回調鏈接返回
Map<String, String> token_name = DouBanOauthBL.grantAccessToken(code);
if(token_name==null){
return false;
}
System.out.println("成功獲得accessToken:"+token_name.get("douban_user_id"));//f9d18d06e5ca9be1ed74a714b15fd3a3
//獲取用戶相關信息
String info = DouBanOauthBL.getUseInfo(token_name);
JSONObject currentUser = (JSONObject)JSONValue.parse(info);System.out.println(currentUser.toJSONString());
------------------------------------DouBanOauthBL.java----------------------------
/**
* 使用授權後的authorization_code換取Access Token
* 因爲豆瓣api在應用沒有通過審覈之錢~me接口不開放,所以先用name頂着
* 封裝普通的Post請求 返回服務端返回json
* {"access_token":"6dd3771561bf6255497a6540253e26ff",
* "douban_user_name":"XXX",
* "douban_user_id":"xxxx",
* "expires_in":604800,
* "refresh_token":"9e74a038d59bf308db5de0aa80d3d918"}
*/
public static Map<String,String> grantAccessToken(String code){
List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();
paramList.add(new BasicNameValuePair("client_id", DouBanAppConfig.oauth_consumer_key));
paramList.add(new BasicNameValuePair("client_secret",DouBanAppConfig.oauth_token));
paramList.add(new BasicNameValuePair("redirect_uri", DouBanAppConfig.redirect_URI+"/sociallogin/dologin?SocialLoginParams=DouBan"));
paramList.add(new BasicNameValuePair("grant_type", "authorization_code"));
paramList.add(new BasicNameValuePair("code",code));
List<String> keys = new ArrayList<String>();//需要返回的信息
keys.add("access_token");
keys.add("douban_user_id");
Map<String,String> token_name = SocailUtil.HttpPost2SNS(paramList,DouBanAppConfig.apiPrefixURL+DouBanAppConfig.accessTokenURL,keys);
return token_name;
}
/**
* 獲取當前授權用戶信息
* 需要授權的Api,需要加access_token的Header,並且使用https協議,限制具體見OAuth2文檔
* 這裏告訴你當應用未通過審覈是,GET /v2/user/~me這個接口不能使用,只能使用GET /v2/user/:name獲取用戶信息;
* :name 爲用戶uid或者數字id
*/
public static String getUseInfo(Map<String,String> token_name){
List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();
Header header = new BasicHeader("access_token",token_name.get("access_token"));
String infoJSON = SocailUtil.HttpGet2SNS(paramList,DouBanAppConfig.OpenIdURL+token_name.get("douban_user_id"),header);
return infoJSON;
}
------------------------------------SocailUtil.java--------------------------
public static Map<String,String> HttpPost2SNS(List<BasicNameValuePair> paramList,String goURL,List<String> backKeys) {
Map<String,String> token_name = null;
try {
HttpPost httpPost = new HttpPost(goURL);
httpPost.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));// 添加請求參數到請求對象
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) { // 爲200表示執行成功
System.out.println("執行成功");
String resultJson = EntityUtils.toString(httpResponse.getEntity()); // 得到返回數據(爲JSON數據)
JSONObject currentUser = (JSONObject)JSONValue.parse(resultJson);
token_name = new HashMap<String,String>();
for(String key : backKeys ){
token_name.put(key,(String)currentUser.get(key));
}
}
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
} catch (Exception e) {
System.out.println("執行失敗:"+e.getMessage().toString());
}
return token_name;
}
public static String HttpGet2SNS(List<BasicNameValuePair> paramList,String goURL,Header header) {
String strResult = null;
try {
String queryURL = appendGetParams(paramList,goURL);
HttpGet httpget = new HttpGet(queryURL);
httpget.addHeader(header);
HttpResponse httpResponse = new DefaultHttpClient().execute(httpget);
if (httpResponse.getStatusLine().getStatusCode() == 200) { // 爲200表示執行成功
System.out.println("執行成功");
strResult = EntityUtils.toString(httpResponse.getEntity()); // 得到返回數據(爲JSON數據)
}
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
} catch (Exception e) {
System.out.println("執行失敗:"+e.getMessage().toString());
}
return strResult;
}
public static String appendGetParams(List<BasicNameValuePair> paramList,String url){
StringBuilder builder = new StringBuilder();
boolean flag = false;
for(BasicNameValuePair bnvp : paramList){
builder.append("&"+bnvp.getName().trim()+"="+bnvp.getValue().trim());
flag = true;
}
if(flag){
url += "?"+builder.toString().substring(1);
}
return url;
}
------------------------------------DouBanAppConfig.java--------------------------
public static final String ID = "DouBanAppConfig";
//App Key
public static final String oauth_consumer_key = "0e3bfd6c9e1edf942ab3f845da5c9ebc";//wjl
//App Secret
public static final String oauth_token = "89672e1e3be1f720";//wjl
//授權回調頁
public static final String redirect_URI = AppContext.getValue().substring(0, AppContext.getValue().length()-1);
//api基礎地址
public static final String apiPrefixURL = "https://www.douban.com/service/auth2/";
/**
* (1)獲取authorization_code
*/
public static final String authorizeURL = "auth";
/**
* (2)獲取access_token
*/
public static final String accessTokenURL = "token";
/**
* (3)根據access_token獲得對應用戶身份信息
* 這裏告訴你當應用未通過審覈是,GET /v2/user/~me這個接口不能使用,只能使用GET /v2/user/:name獲取用戶信息;
*/
//public static final String OpenIdURL = "https://api.douban.com/v2/user/~me";
public static final String OpenIdURL = "https://api.douban.com/v2/user/";
小結:
1:豆瓣對於未通過審覈上線的應用,GET /v2/user/~me這個接口不能使用,只能使用GET /v2/user/:name獲取用戶信息
2:在請求的時候注意區分是Get還是Post方式
3:豆瓣在訪問需要授權的API的時候需要在header中加入accesstoken
4:豆瓣在測試的時候注意添加測試賬號
5:在創建應用的時候注意回調地址與我們應用中的鏈接調用中的回調地址保持一致
6:其他的社會化登錄方式,QQ/Sina/BaiDu的都做的不錯,人人的比較萬惡,豆瓣的比較亂,不過總體的配置和使用都差不多,QQ對回調的設置驗證比較嚴格,BaiDu的文檔非常清晰明瞭。
7:一些OAuth2.0授權過程中需要驗證用戶的身份,支持Cookie驗證。已經使用OAuth2.0登錄的瀏覽器,不會再次出現登陸頁面。 如果需要強制切換賬號
人人:可以在請求https://graph.renren.com/oauth/authorize時傳遞“x_renew=true”。
新浪:授權頁會默認讀取當前用戶的新浪微博登錄狀態,如果你想讓用戶重新登錄,請在調用authorize接口時傳入參數:forcelogin=true
豆瓣:自帶
百度:confirm_login=1
騰訊:自帶
8:QQ互聯的創建應用需要網站驗證,這個過程需要等待一段時間,不能使用localhost/127.0.0.1,所以建議方法:修改自己的hosts文件,添加域名
9:豆瓣比較特殊,在獲取access_token的時候就會把授權的用戶id直接返回。
10:百度對於URL訪問另外需要配置: