This time the project will be able to use Sina Weibo, QQ Internet and Facebook and Twitter authorized login
Facebook currently only supports OAUTH2 technology, personal understanding of its workflow is when users want to access the current site, but do not want to register an account, at this time the current site has other major sites of third-party login support features, even with the current site of the website's account password to third-party cooperation site to verify the legality of users, Successful authentication allows you to log in to the current site without knowing the password of the third party's account.
You need to register a Facebook app before development, so you get two values like keys, client_id and Client_secret, which are the necessary parameters to access the Facebook URL;
Also need to make some necessary settings for the app, first to set up access to Facebook and Facebook callback domain name, and configure the white list, which is the IP value, multiple comma separated, Facebook will verify the current access to the domain name after the corresponding IP is in the whitelist;
Next note that the sandbox option must not be enabled, otherwise it will not get the user's information, so that the Facebook app basic settings are complete, it is time to start writing the request code.
Here's a look at the Oauth2 workflow, and then we'll see the steps and principles.
When the user clicks the Third Party login button, it will jump out the login page of the third Party website (hereinafter referred to as the server), enter the user name password after the client will request a temporary token (i.e. code value) to the server, the client must also apply for authorization (that is, token value) after successful application. If it is the first visit will jump out of the authorization page, the user is allowed to access some of its basic information, such as name, email, user ID, picture and other basic information, if authentication and authorization through, then log in to the current site, and the next time the default is selected before the authorization will not pop-up, unless the local cookie is cleared.
Now let's write the code and first look at some basic parameters and access URLs for Facebook oauth2.
Basic parameters:
1. client_id = 107717212399602//value for registered application
2, RedirectURL = Http://blog.csdn.net/webgeek//For Facebook callback the URL of the current site
3, SCOPE = "&scope=user_about_me,email,read_stream"; The permission range that represents the obtained user information
Access URL:
1, Request_code_url//Send, get authorization CODE
Https://www.facebook.com/dialog/oauth "+" client_id= "+client_id+" &redirect_uri= "+redirecturl+" &response _type=code "+scope;
2, Request_token_url//Request TOKEN URL
Https://graph.facebook.com/oauth/access_token
3. Request_user_url//Use of the obtained token to obtain user information
Https://graph.facebook.com/me
There's no use of Facebook's official packaged tool class, because having access to the URL (provided by the official API) is actually the process of sending an HTTP request and receiving a response, so the next step is to write the HTTP process.
In code 1-controller:
public void Visiturl (string code, @Param ("Origurl") string origurl) {
try {
if (Origurl! = NULL &&! "". Equals (Origurl)) {
This.origurl = Origurl;
}
Get a response object that you can get in your own way
HttpServletResponse response = Inv.getresponse ();
if (code! = NULL &&! "). Equals (code)) {
String token = nuomioauthapi.getfacebookaccesstoken (code);
if (token = = NULL | | "". Equals (token)) {
Response.getwriter (). Write ("Get code Error ...");
}else {
string[] tokens = Token.split ("&");
for (String T:tokens) {
if (T.indexof ("Access_token")! =-1) {
There is a possibility that the value returned here has excess data that can be used to determine whether to process token = t.split ("=") according to the actual development situation [1].trim ();
}
}
Call here to verify through the user's basic information map<string, string> Map = Getloginuser (token);
if (map! = null) {
Here is to determine whether the local already has this user, whether need local registration, can get user information after self-developed this.isloginuseroldornew (INV, map, Origurl);
}else {
Response.sendredirect (Iniuxconstants.domain_tw+origurl);
}
}
}else {
Here is the first time the code value is applied
Response.sendredirect (Requestcodeurl);
}
} catch (Exception e) {
E.printstacktrace ();
}
}
Code 2-:
/**
* Use authentication code method to obtain Acesstoken
* @param authcode
* @return
* If wrong, return null
*/
public static string Getfacebookaccesstoken (String authcode) {
try {
StringBuffer urlstr = new StringBuffer (Request_token_url);
Urlstr.append ('? ');
StringBuffer temp = new StringBuffer ();
Temp.append ("client_id="). Append (client_id). Append (' & ')
. Append ("redirect_uri="). Append (RedirectURL). Append (' & ')
. Append ("client_secret="). Append (Client_secret). Append (' & ')
. Append ("Grant_type=authorization_code"). Append (' & ')
. Append ("code=" + Authcode);
Urlstr.append (Temp.tostring ());
Log.info ("Urlstr:" +urlstr);
String token = Getfacebooktokenfromurl (urlstr.tostring (), NULL);
Log.info ("Get token by Authcode:" +token);
return token;
} catch (Exception ex) {
Log.error ("Get Accesstoken Error:" + ex.getmessage (), ex);
return null;
}
}
Code Listing 3:
/**
* Access to pre-recorded user information via API and Token
* @param token
* @return
* Map of Id/name; return null if wrong
*/
public static map<string, string> Getloginuser (String token) {
try {
StringBuffer urlstr = new StringBuffer (Request_user_url);
Urlstr.append ("?"). Append ("access_token=" +encodeurl (token));
Log.info ("Getloginuser urlstr:" +urlstr.tostring ());
Jsonobject json = Getfacebookjsonfromurl (urlstr.tostring (), NULL);
Log.info ("Getloginuser JSON:" +json);
if (!json.containskey ("id")) {
if (Json.containskey ("Error_reason")) {
String Errorreason = json.getstring ("Error_reason");
String errordescription = json.getstring ("error_description");
Log.warn ("Save to Facebook failed. Errorreason: "+ Errorreason +", ErrorDescription: "+ errordescription);
}
} else {
map<string, string> userInfo = new hashmap<string, string> ();
Userinfo.put ("id", json.getstring ("id"));
Userinfo.put ("Name", Json.getstring ("name"));
Userinfo.put ("Email", json.getstring ("email"));
Userinfo.put ("Gender", json.getstring ("gender"));
return userInfo;
}
} catch (Exception e) {
Log it
Log.error ("Get user info failed ...", e);
E.printstacktrace ();
}
Return null;//Error
}
Code Listing 4:
/**
* Extract JSON from specific URLs
* @param urlstr
* @param params
* @return
* JSON object, or null if failed
*/
private static Jsonobject Getfacebookjsonfromurl (String urlstr, map<string, string> params) {
HttpClient HttpClient = new Defaulthttpclient ();
HTTP please do not support post mode, but support get
HttpGet httpget = new HttpGet (URLSTR);
Jsonobject json = NULL;
try {
HttpResponse response = Httpclient.execute (HttpGet);
httpentity entity = response.getentity ();
InputStream is = Entity.getcontent ();
String aStr = ioutils.tostring (IS);
JSON = Jsonobject.fromobject (ASTR);
} catch (Exception e) {
Log.error ("HTTP Client Execute Error:" + e.getmessage (), E);
}
return JSON;
}
The above is the entire development process, there are a few points to note:
1, the URL of the sending request has a callback URL (that is, RedirectURL in the code), this parameter in the request code and token when the value must be consistent, otherwise cannot be authorized
2, send the URL string should encode, the browser will automatically parse
3. When sending user information request, make sure to send HTTP request with Get method
Third-party login development-facebook