Spring Security and Integration with OAuth 2.0 with Graph API

Please, at least pseudo (but from the working environment, and not “maybe this should work”), the application context and the controller / filter, which will authenticate and / or automatically register Facebook users.

This link: http://blog.kadirpekel.com/2009/11/09/facebook-connect-integration-with-spring-security/ will not do. In fact, I will put a minus to indicate anyone who will publish it as an answer. I spend 2 hours with this and I have not got it to work. I ended up a bit bolder and felt more dumb than usual after this endeavor :-(

I would really like to see OAuth 2.0 for connecting to facebook. And limit your use of the JavaScript JavaScript API to an absolute minimum.

The following link shows what I need: http://www.richardnichols.net/2010/06/implementing-facebook-oauth-2-0-authentication-in-java/

Please post only the code for this question. I already have all the tips I can handle.

UPDATE

I have a solution for servlets and posted here if anyone is interested: Facebook Connect example in JSP (tomcat)

+8
java spring spring-security facebook facebook-graph-api
source share
2 answers

This is where the MVC version of facebook OAuth 2.0 is implemented. Code in C # and hopefully its similarity to java will help you.

Controller (entry point): The controller (in MVC) is the point in the code at which the control reaches after someone clicks on the entry link.

public ActionResult Authenticate() { var oauthFacebook = new FacebookOAuth(); if (Request["code"] == null) { //Redirect the user to Facebook for authorization. Response.Redirect(oauthFacebook.AuthorizationLinkGet()); } else { //Get the access token and secret. oauthFacebook.AccessTokenGet(Request["code"]); if (oauthFacebook.Token.Length > 0) { //We can now make our api calls var user = oauthFacebook.GetAttributes(); } } } 

FacebookOAuth Class

 public class FacebookOAuth : Oauth { public FacebookOAuth() { Authorize = "https://graph.facebook.com/oauth/authorize"; AccessToken = "https://graph.facebook.com/oauth/access_token"; CallbackUrl = "http://<YourURLHere>/Authenticate"; AttributesBaseUrl = "https://graph.facebook.com/me/?access_token="; ConsumerKey = ConfigurationManager.AppSettings["FacebookConsumerKey"];//Ur Consumer Key goes here ConsumerSecret = ConfigurationManager.AppSettings["FacebookConsumerSecret"];//Ur Consumer secret goes here Provider = "Facebook"; } public override string AuthorizationLinkGet() { return string.Format( "{0}?client_id={1}&redirect_uri={2}&scope=email,user_education_history,user_location,user_hometown", Authorize, ConsumerKey, CallbackUrl); } public User GetAttributes() { string attributesUrl = string.Format("{0}{1}", AttributesBaseUrl, Token); string attributes = WebRequest(Method.Get, attributesUrl, String.Empty); var FacebookUser = new JavaScriptSerializer().Deserialize<FacebookUser>(attributes); return new User() { FirstName = FacebookUser.first_name, MiddleName = FacebookUser.middle_name, LastName = FacebookUser.last_name, Locale = FacebookUser.locale, UserEmail = FacebookUser.email, AuthProvider = Provider, AuthToken=Token }; } } 

OAuth baseclass (the class FacebookOAuth comes from)

  public abstract class Oauth { #region Method enum public enum Method { Get, Post, Delete } ; #endregion protected string AccessToken; protected string AttributesBaseUrl; protected string Authorize; protected string CallbackUrl; protected string ConsumerKey; protected string ConsumerSecret; public string Provider { get; protected set; } public string Token { get; set; } public virtual string AuthorizationLinkGet() { return string.Format( "{0}?client_id={1}&redirect_uri={2}&scope=publish_stream,email,user_education_history,user_location", Authorize, ConsumerKey, CallbackUrl); } public void AccessTokenGet(string authToken) { Token = authToken; string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}", AccessToken, ConsumerKey, CallbackUrl, ConsumerSecret, authToken); string response = WebRequest(Method.Get, accessTokenUrl, String.Empty); if (response.Length > 0) { //Store the returned access_token NameValueCollection qs = HttpUtility.ParseQueryString(response); if (qs["access_token"] != null) { Token = qs["access_token"]; } } } public string WebRequest(Method method, string url, string postData) { StreamWriter requestWriter; string responseData = string.Empty; var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; if (webRequest != null) { webRequest.Method = method.ToString(); webRequest.ServicePoint.Expect100Continue = false; webRequest.Timeout = 20000; if (method == Method.Post) { webRequest.ContentType = "application/x-www-form-urlencoded"; //POST the data. requestWriter = new StreamWriter(webRequest.GetRequestStream()); try { requestWriter.Write(postData); } finally { requestWriter.Close(); } } responseData = WebResponseGet(webRequest); } return responseData; } public string WebResponseGet(HttpWebRequest webRequest) { StreamReader responseReader = null; string responseData; try { responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } finally { if (webRequest != null) webRequest.GetResponse().GetResponseStream().Close(); if (responseReader != null) responseReader.Close(); } return responseData; } } 
+3
source share

I actually just completed my non-javascript implementation of the Facebook Graph API authentication last night. I was a giant pain in **, but it works and it works quite well.

I used the example from the above link as a starting point, and also the code here as a starting point. I had to write my own implementation of my FacebookGraphAuthenticationProvider and my FacebookGraphAuthenticationFilter, but now it works the way I want it.

You need to create implementations of both of these files, put the filter in the filter chain and create an implementation of User Security WettyService>, which the provider can use to manage your user account. I have a code on my car at home, and I can send you an email if you want.

Here are the steps I should have used to get authentication working:

  • To get the "code" for the user, this is done by the following call: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream (the area is all the permissions that you want to request from FB). This call will create an "authentication code" which will then be sent back to your "redirect_uri" (which I called http: // {registered domain domain fb] / j_spring_security_authentication_check.

  • Once you have this “code”, you need to make a call in your AuthenticationProvider that will receive the access_token for your user session: this URL looks like this: https://graph.facebook.com/oauth/access_token ? client_id = YOUR_APP_ID & redirect_uri = YOUR_URL & client_secret = YOUR_APP_SECRET & code = THE_CODE_FROM_ABOVE. You need to make sure your "redirect_uri" is the same as the one you made in # 1. You will make the above call using something like Apache HttpClient or the like.

  • Now with this access_token (which goes into the body above the answer) you can get information about your user profile at the following URL: https://graph.facebook.com/me?access_token= {ACCESS_TOKEN above). The answer will be in JSON. You can also use access_token with the entire graphical API to post status, images, etc.

I have a house code that has my full implementation, and I would be happy to share it.

Hope this helps at least a little. I suggest using the Spring social app to get started with publication status, pictures, wall materials, etc. This will be a good place to start interacting with FB-Spring.

+3
source share

Source: https://habr.com/ru/post/650891/


All Articles