SocialAuth java library working with google account - java

I'm facing an issue in socialAuth java library. I used that library for logging to my app by using social networks. Login with Facebook is working properly. But when i try to use google and yahoo is does not work for me. Error occur when after authentication process, redirection part is not working properly,
#SuppressWarnings("unused")
#RequestMapping(params = "code")
private String oauth2Callback(final HttpServletRequest request,
HttpServletResponse response,
Model model) throws Exception {
String serviceReturnUrl = request.getParameter("service");
String clientAppKey = request.getParameter("app_key");
org.brickred.socialauth.AuthProvider provider = null;
SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
if (manager != null) {
try {
provider = manager.connect(SocialAuthUtil.getRequestParametersMap(request));
} catch (Exception e) {
e.printStackTrace();
}
} else {
response.sendRedirect(appLoadConfigurer.getProperty("caslk"));
return "";
}
When redirecting Facebook to my app this method catch the request. but when it comes to google, i could not catch the request from google by using this method. request is not comes to here. Any one can idea to fix my issue as soon as possible

For google you will have to use
#RequestMapping(params = "openid.claimed_id")
Because google doen't return any attribute with name 'code' that's why it is not matching with this.

Related

unable to hit SAML SLO single log out request to OKTA

I am trying to implement SAML SLO with OKTA , i am able to integrate SSO Login using OpenSAML4 but to implement SLO with Okta ,i am not getting proper resource.
My project is servlet based only and for logout Rest endpoint is already created which is called from react UI and invalidates session .
https://blog.samlsecurity.com/2012/11/verifying-signatures-with-opensaml.html
i am following the above blog , but it seems i am missing something , is there any resource or working example which i can refer or any improvement in the mentioned blog which can help me to implement SLO
private void redirectUserWithRequest(HttpServletResponse httpServletResponse, AuthnRequest authnRequest) {
MessageContext context = new MessageContext();
context.setMessage(authnRequest);
SAMLBindingContext bindingContext = context.getSubcontext(SAMLBindingContext.class, true);
bindingContext.setRelayState("teststate");
SAMLPeerEntityContext peerEntityContext = context.getSubcontext(SAMLPeerEntityContext.class, true);
SAMLEndpointContext endpointContext = peerEntityContext.getSubcontext(SAMLEndpointContext.class, true);
endpointContext.setEndpoint(URLToEndpoint(MESSAGE_RECEIVER_ENDPOINT));
HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder();
encoder.setMessageContext(context);
encoder.setHttpServletResponse(httpServletResponse);
try {
encoder.initialize();
} catch (ComponentInitializationException e) {
throw new RuntimeException(e);
}
logger.info("Redirecting to receiver with AuthnRequest");
try {
encoder.encode();
} catch (MessageEncodingException e) {
throw new RuntimeException(e);
}
}

Facebook OAuthException : Malformed Access Token ErrorCode 190

I have been battling this problem for hours now and I seem to get nowhere with it. So, I have successfully asked the users to login using Facebook to my android app.
Once they are logged in, I get the access token (a string value) and then use it to make a Request to Facebook to fetch a Page's Posts. Here is how I do that whole process.
public void setupFacebook()
{
Session.openActiveSession(this, true, new Session.StatusCallback()
{
// callback when session changes state
#Override
public void call(Session mSession, SessionState state, Exception exception) {
if (mSession.isOpened() && mSession != null)
{
facebookAccessToken = mSession.getAccessToken();
Log.d("ACCESSTOKEN", facebookAccessToken);
fetchPagePosts(facebookAccessToken, mSession);
}
}
});
}
public void fetchPagePosts(String token, Session session)
{
Request.Callback callback = new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
Log.d("RESPONSE", "ERROR"+response.getError());
Log.d("RESPONSE", ""+response);
}
};
String endpoint = String.format("https://graph.facebook.com/"+pageId+"/posts?access_token=%s", facebookAccessToken);
Log.d("ENDPOINT", endpoint);
Request request = new Request(session, endpoint, null, HttpMethod.GET, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
The interesting part here is that when I copy the url from my Logcat (what I called endpoint) and paste to my browser, it works perfectly fine.
When I run my code on my tablet though, it returns the ErrorCode 190 and HttpStatus 400.
According to Facebook's documentation, it could be one of several things;
Access token is invalid
It is expired
The user has changed their password or
The user has logged out of their account
The user has revoked access to their account by your app!
I am stuck here because I have tested the same URL on the browser and it returns the json data I need. It just fails when am running it in android code.
If anyone has suggestions, please help me - will be truly thankful for your help.
Thank you in advance.
You could try using the Simple Facebook Android library instead of the Facebook SDK https://github.com/sromku/android-simple-facebook, its a lot simpler.

How to make a request for an access token using the refresh token with Google OAuth 2.0

i think the context of my question is clear enough, but i would like to specifiy that i'm using a OAuth for Web Application, so I used this Example provided by Google: OAuth 2.0 for WebApplication
I understood that i have to create (for example in the same class (extended by HttpServlet)) a doGet method (obviously in Override) to obtain the correct flow to authorize the user with own scopes, so something like this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//This is a class to obtain the Current Google User's ID
UserService userService = UserServiceFactory.getUserService();
String userId = userService.getCurrentUser().getUserId();
String url = getAuthorizationUrl(userId);
if(req.getParameter("code")!=null){
try {
String authorizationCode = req.getParameter("code");
getCredentials(authorizationCode);
} catch (CodeExchangeException | NoRefreshTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the next page (my homePage)
resp.sendRedirect("/home");
}
else{
resp.sendRedirect(url);
}
}
This successfully work, if you look at the provided method 'getCredential(authorizationCode)' it shows 2 method: storeCredential and getStoredCredential.
The first method works perfectly and i can see the refreshToken and accessToken strings in my Datastore indeed.
The problem is to build the getStoredCredential method, because it returns a Credential object and i don't know to write it. I show you the beginning of the method but i don't know how to carry on.
static Credential getStoredCredentials(String googlePlusUserId) {
// TODO: Implement this method to work with your database. Instantiate a new
// Credential instance with stored accessToken and refreshToken.
//These methods of my Class correctly get the tokens (already debugged)
String refreshToken = UserManager.getStoredRefreshToken(googlePlusUserId);
String accessToken = UserManager.getStoredAccessToken(googlePlusUserId);
//How can i continue here? :-( to return Credential with correct parameters?
//......
//......
//......
//......
}
Does this method works forever?
Because in Google OAuth Playgroung there is a checkbox that says: "Auto-refresh the token before it expires" (i think in 3600 seconds). So, i don't think that completing my getStoredCredential get my App working correctly...I think that is only useful for get always the last token...So in this case i can never obtain a new accessToken using the Stored RefreshToken.
Does anyone can help me please? Maybe with a simple method that refresh the old AccessToken.

Can I develop a Desktop App for LinkedIn using Java?

I was wondering if I can develop a Desktop App for LinkedIn using Java. I know it can be done as a web application easily, but a completely desktop application, is it possible?
I had a look at the linkedin api's and Java Wrapper for LinkedIn.
The code was explained for a web application. How do I manage that in a java desktop app, specifically the authorization part?
oAuth using Swing?
Please direct me in the right way.
After a very long time of testing with oAuth (with my own wrappers), I settled for Scribe which is a Java Wrapper for almost all oAuth mechanisms. To include Linkedin in a Desktop client, as Adam Trachtenberg (Thank you again) suggested, oob option was used, i.e., after logging in, a code generated by linkedin has to be entered in our Client so that it can be validated against the requested url. Hope this is useful for someone.
public class LinkedInExample
{
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(id,last-name)";
public static void main(String[] args) throws IOException
{
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey("YourApiKey")
.apiSecret("YourApiSecret")
.build();
Scanner in = new Scanner(System.in);
//BareBonesBrowserLaunch.openURL("www.google.com");
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
String authURL = service.getAuthorizationUrl(requestToken);
System.out.println(authURL);
BareBonesBrowserLaunch.openURL("www.google.com");
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
The BareBonesBrowserLaunch is used to launch the default browser with the Linkedin URL for the token request in most OS's. Since the Desktop part is not available in Java 1.5, the BareBonesBrowserLaunch solves the problem.
public class BareBonesBrowserLaunch {
static final String[] browsers = { "google-chrome", "firefox", "opera",
"epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla" };
static final String errMsg = "Error attempting to launch web browser";
public static void openURL(String url) {
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,
new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString());
}
}
}
}
The LinkedInExample is taken mostly from this library - https://github.com/fernandezpablo85/scribe-java/downloads
Don't forget to include the Scribe jar and apache commons-codec (for Base64)
Yes you can it's all about playing with the API and utilizing the web services packed within the LinkedIn's API.
However, the entire process has to be implemented by using the HTTP requests etc and by parsing the response to render it on the JForm.
EDIT: Ahh! you are totally independent :-) thanks to XML..
If you can't figure out how to redirect the user to a web browser and have the browser redirect back to your application, check out the "out of bounds" (aka "oob") option for the OAuth callback. This will display a code to the member after they authorize your application, which they can type into your Java app.

Spring Security & Facebook OAuth 2.0 Integration with Graph API

Please, at least pseudo (but from working environment not "maybe this should work") application context and controller/filter that will authenticate and/or auto-register Facebook users.
This link: http://blog.kadirpekel.com/2009/11/09/facebook-connect-integration-with-spring-security/ will not do. Actually I will put minus point to anyone who will post it as answer. I spend 2 hours with the thing and I didn't get it to work. I ended bit more bolder and feeling more stupid than usual after this endeavor :-(
I would really like to see OAuth 2.0 solution for facebook connect. And restrict the use of Facebook JavaScript API to absolute minimum.
Following link shows about what I need:
http://www.richardnichols.net/2010/06/implementing-facebook-oauth-2-0-authentication-in-java/
Please post only code to this question. I already got all the advice I can handle.
UPDATE
I have servlet solution and posted answer here if anyone is interested:
Facebook Connect example in JSP (tomcat)
Here's an MVC implementation of facebook OAuth 2.0
The code's in C# and hopefully its similarity with java helps you out.
Controller(Entry point):Controller(in MVC) is the point in the code where the control reaches after someone clicks on the login 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(Class from which FacebookOAuth derives)
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;
}
}
I actually just finished my non-javascript, implementation of the Facebook Graph API Authentication last night. I was a gargantuan pain in the a**, but it works and it's working fairly well.
I used the example from the link you posted above as a starting point, as well as, the code from here as a starting point. I had to write my own implementation of their FacebookGraphAuthenticationProvider and their FacebookGraphAuthenticationFilter, but now it works the way I want it to.
You need to create implementations of both of these files, put your filter in the filter chain, and create a implementation of the Spring Security UserDetailsService that the Provider can use to manage your user account information. I have some code on my machine at home that I can send you via email if you like.
Here are the steps I had to use to get the authentication to work:
Get an "code" for a user, this is done by making the following call: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream (The scope is all the permissions 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 stated as http://{my fb app registered domain}/j_spring_security_authentication_check.
Once you have this "code", you need to make a call within your AuthenticationProvider that will retrieve an access_token for your user's session: this URL looks like: 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 have to make sure your "redirect_uri" is the same as the one you did in #1. You'll make the above call using something like Apache's HttpClient, or the like.
Now with this access_token (which comes in the body of above response), you can get your user's profile information with the following URL: https://graph.facebook.com/me?access_token={ACCESS_TOKEN from above). The response will be in JSON. You can also use the access_token with all of the graph API to post status, pictures, etc.
I have some code at home that has my full implementation that I would be happy to share.
I hope this helps at least a bit. I suggest using the Spring Social app to get started with posting status, pictures, wall stuff, etc. This will be a good place to start looking at FB-Spring interaction.

Categories

Resources