Salesforce OAuth Access_Token null? - java

I am trying to implement the rest api sample given in the salesforce site link below.
http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_REST_API
I have set up project as said in the link, but when I am executing the project I am getting an error as "Error - no access token". When I do debug, I came to know that the variable accessToken is null.
String accessToken = (String)
request.getSession().getAttribute("ACCESS_TOKEN");
I am bit confused about this problem.
Please help me in this regard.

It seems you are missing this part in your code:
// Set a session attribute so that other servlets can get the
// access token
request.getSession().setAttribute(ACCESS_TOKEN, accessToken);
// We also get the instance URL from the OAuth response, so set it
// in the session too
request.getSession().setAttribute(INSTANCE_URL, instanceUrl);

Related

SAML implementation using OneLogin in ColdFusion throwing error

As part of learning how to integrate OneLogin SSO in my ColdFusion app I pulled this git repo -
https://github.com/GiancarloGomez/ColdFusion-OneLogin and set up locally. But, while sending the auth request to OneLogin we are getting an error message saying "We're sorry, but something went wrong.
We've been notified about this issue and we'll take a look at it shortly."
I could not find the root cause of this issue. Appreciate your timely help on this.
Configuration on OneLogin looks like below. Note that consumer URL I modified to http://127.0.0.1:8500/coldfusion-onelogin/consume.cfm instead of actual format mentioned (http://127.0.0.1:8500/coldfusion-onelogin/consume/) in the YouTube video provided in the readme file of this git repo. I had tried changing the consumer URL format as this http://127.0.0.1:8500/coldfusion-onelogin/consume/ but we are still getting the error message.
Access Tab in OneLogin looks like below,
Below is the code which sends auth request to OneLogin.
<cfscript>
try{
// used to encode string - chose to use Java version just in case CF did not encode correctly
// encodeForURL appears to work but to keep the same as the samples from OneLogin I will use the Java reference
urlEncoder = createObject("java","java.net.URLEncoder");
// the appSettings object contain application specific settings used by the SAML library
appSettings = createObject("java","com.onelogin.AppSettings");
// set the URL of the consume file for this app. The SAML Response will be posted to this URL
appSettings.setAssertionConsumerServiceUrl(request.company.getConsumeUrl());
// set the issuer of the authentication request. This would usually be the URL of the issuing web application
appSettings.setIssuer(request.company.getIssuerUrl());
// the accSettings object contains settings specific to the users account.
accSettings = createObject("java","com.onelogin.AccountSettings");
// The URL at the Identity Provider where to the authentication request should be sent
accSettings.setIdpSsoTargetUrl("https://app.onelogin.com/saml/signon/" & request.company.getIssuerID());
// Generate an AuthRequest and send it to the identity provider
authReq = createObject("java","com.onelogin.saml.AuthRequest").init(appSettings, accSettings);
// now send to one login
location ( accSettings.getIdp_sso_target_url() & "?SAMLRequest=" & authReq.getRidOfCRLF(urlEncoder.encode(authReq.getRequest(authReq.base64),"UTF-8")), false);
}
catch(Any e){
writeDump(e);
}
</cfscript>
Below is the format of auth request URL ,
https://app.onelogin.com/saml/signon/[issuerId]?SAMLRequest=[SamlRequest].
I am not providing the actual URL here since I am not sure whether someone can tamper it or not. But please do let us know if it is really required to solve this issue.
Below is the screenshot of the SAML Login Page , from here I am clicking on the button and send auth request to OneLogin.
Also, In the index.cfm , form action attribute is "/post/". Since it was throwing an error I had to replace it with "/coldfusion-onelogin/post.cfm". Here coldfusion-onelogin is a folder under wwwroot. Any settings in ColdFusion to be modified so that it will not throw any error if we keep the form action attribute as "/post/" ?.
Hmmm. The consumer URL validator is supposed to be a regex expression, and I'm not sure how it's going to handle a literal HTTP value (since it'll try to evaluate it as regex)
So try changing URL validator to be something dumb like *. (match everything)
That should hopefully clear the error until you can sort out what you want the validation to be in production.
You need to first logout from the OneLogin Admin Panel
https://app.onelogin.com/logout
To successfully test the demo app.

Google API Authorization Using Scribe OAuth Java Library

I am trying to make a Java class which would call upon Google's API to recreate an access token to a user's account with new permissions/larger scope. This class is to be instantiated by a Java servlet I had created. I want a function within that class to return a new access token. For this class to do that, I am using the Scribe library.
In Scribe's quick guide, there are two steps which concern me and have me stumped:
Step Three: Making the user validate your request token
Let’s help your users authorize your app to do the OAuth calls. For
this you need to redirect them to the following URL:
String authUrl = service.getAuthorizationUrl(requestToken);
After this either the user will get a verifier code (if this is an OOB
request) or you’ll receive a redirect from Twitter with the verifier
and the requestToken on it (if you provided a callbackUrl)
Step Four: Get the access Token
Now that you have (somehow) the verifier, you need to exchange your
requestToken and verifier for an accessToken which is the one used to
sign requests.
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
It does not seem to specify how to get that verifier from the user. How am I supposed to do that? How do I redirect my user to the authURL, and how do I get it to send its verifier back to this class of mine, which initiated the request to begin with?
If this is unclear, let me structure the question differently, taking Scribe out of the equation: To get an authorization code from Google (which would be used to then get a refresh token and access token), I would execute the following URL connection from within the servlet (yes, I've tried to answer this problem without the Scribe library, and still can't figure it out):
URL authURL = new URL("https://accounts.google.com/o/oauth2/auth");
HttpsURLConnection authCon = (HttpsURLConnection) authURL.openConnection();
authCon.setRequestMethod("GET");
authCon.setDoOutput(false);
authCon.setConnectTimeout(100000);
authCon.setRequestProperty("response_type", "code");
authCon.setRequestProperty("client_id", CLIENT_ID);
authCon.setRequestProperty("redirect_uri",
"http://**************.com/parseAuth/");
authCon.setRequestProperty("scope", convertToCommaDelimited(scopes));
authCon.setRequestProperty("state", csrfSec);
authCon.setRequestProperty("access_type", "offline");
authCon.setRequestProperty("approval_prompt", "auto");
authCon.setRequestProperty("include_granted_scopes", "true");
What has me stuck is what I should be putting for the redirect URI. After getting the user's approval for the new scope, this authorization URL would return an authorization code to the redirect URI, and seemingly nothing to whatever called it. (Am I correct in this?) So if I have another servlet as the redirect URI to parse/extract the authorization code from the response, how in the world do I get that authorization code back to my first, initial servlet? It seems to me that there is no way to have it give back the value to the servlet, in the same position of the code from which the URL was called. It looks like the function has to end there, and all new action must take place within that new servlet. But if that is the case, and I send that auth code to Google's API which would send back a refresh token and access token to ANOTHER servlet I would make to be its redirect URI, how do I possibly get that information back to what it is which called the initial servlet to begin with? That seems to be the same problem at its core, with the problem I am having with Scribe.
I've been stuck on this for many hours, and can't seem to figure out what it is I am supposed to do. I feel like I am missing some key concept, element, or step. I need this clarified. If it is at all relevant, my servlet is hosted on a Jboss application server on OpenShift.

Facebook OAuth redirect_uri Issue

I am trying to build authentication flow in our app for facebook in java. I am using facebook4j library.
My corresponding code is as follows -
public String authenticate() throws IOException {
Facebook facebook = new FacebookFactory().getInstance();
String redirectURL = facebook.getOAuthAuthorizationURL("http://localhost:9099/default/facebook/verify.html");
servletResponse.sendRedirect(redirectURL);
return null;
}
public String verify() throws Exception {
String code = servletRequest.getParameter("code");
Facebook facebook = new FacebookFactory().getInstance();
AccessToken accessToken = facebook.getOAuthAccessToken(code);
String token = accessToken.getToken();
servletResponse.getWriter().write(token);
return null;
}
I am getting error after redirection on this line -
AccessToken accessToken = facebook.getOAuthAccessToken(code);
The error is as follows -
FacebookException{statusCode=400, errorType='OAuthException', errorMessage='redirect_uri isn't an absolute URI. Check RFC 3986.', errorCode=191, errorSubcode=-1, version=2.2.2}
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:179)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:97)
at facebook4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:107)
redirectURL that I am getting from facebook in first call is -
https://www.facebook.com/dialog/oauth?client_id=4161XXXXXX6389&redirect_uri=http%3A%2F%2Flocalhost%3A9099%2Fdefault%2Ffacebook%2Fverify.html&scope=email,public_profile,user_friends
tried without using encoding too -
https://www.facebook.com/dialog/oauth?client_id=4161XXXXXX6389&redirect_uri=http://localhost:9099/default/facebook/verify.html&scope=email,public_profile,user_friends
It is redirecting properly to 'verify' having url something like -
http://localhost:9099/default/facebook/verify.html?code=AQCE4aaIpE_c94J3NVNjge_YL_OP84vPIgUauvfRRXNCj_FOK8U2kfSxfKGrjWnFL1dqMeM8q22M6UaVbGsTpTQOQmjxYILdFHKFiSFd0Ycf_ByBE9rNX_yxvFnJ3RNLf7bjCT4C1uXuuqCXHZjVNN1lBb3LWUHz7eNkq0r8K14x7ZEVIWjbll-Vqys1FZuCIVDBrI4StoYkZR1rpCsoSqq7VdCIX3zawnw_nbPZBZU7iUeZJiBbahYjWkHIn47b9AQb3hZxxpe4xxXHXfDsP_h2fhC1YYioJbwGq4QbnWpUrP7aF-0Q_wF71zn4txCQLd4#=
facebook4j.properties
oauth.appId=416XXXXXXXXX389
oauth.appSecret=9ed3XXXXXXb6acXXXXXXXXc7acXXXX5
oauth.permissions=email,public_profile,user_friends
My Facebook App basic settings are -
The important advanced settings are -
I am totally aware that similar question has been posted earlier multiple times. I have gone through almost every question & I tried almost everything suggested to resolve this issue. But due to some reason it is not working. I decided to post my problem here after spending 3 days on the same issue.
I would highly appreciate if someone points out where exactly am I going wrong.
The redirect_uri parameter has to be specified when exchanging the code for a token as well (and has to be the same as specified earlier in the login dialog call).
I’d assume that since you are using new FacebookFactory().getInstance() in your second method, that is not the case. Take a look at the basic implementation here, https://github.com/roundrop/facebook4j-oauth-example/tree/master/src/main/java/facebook4j/examples/signin
In SignInServlet, the Facebook object instance is stored into the session, and then in CallbackServlet that same instance is retrieved and used again. Therefor, it still holds the redirect_uri value that was initially used when the Auth dialog was called, and will re-use that same value when exchanging the code for a token.

Scribe - restore access token with code (OAuth2 vs OAuth1)

In an OAuth1 process, I save my token and my secret and recreate my access token like the following:
accessToken = new Token(token, secret);
In an OAuth2 process, I only get a code. If I save this code and try to recreate the access token like following, the app crashes:
Verifier v = new Verifier(code);
accessToken = service.getAccessToken(null, v);
The response:
org.scribe.exceptions.OAuthException: Cannot extract an acces token. Response was: {"code": 400, "error_type": "OAuthException", "error_message": "No matching code found."}
How do I recreate an access token in an OAuth2 process?
I think the problem here is not with your Java code to extract the token (the bit that you're showing at least) - that looks fine from what I can tell.
The error message is a response back from the service you're trying to authorize with (e.g. twitter, or whatever it is in your case) saying that
code
is not known. That could happen if too much time has passed since you got that authorization code from the service, or simply that the authorization code you have is wrong for some reason.
In order to provide proper answer, I'd need to see a bit more code... how precisely are you getting the value of
code
that is going into the constructor of
Verifier
? Please can you provide more of the code you're using for that?
[Sorry, I would have added this as a comment, but don't have enough reputation.]

how to get access token using gdata in java

I am developing a Java Application where I am implementing 3-legged OAuth using google gdata in Java. This application is registered on Google App Engine. At the first stage, I am getting the unauthorized request-token successfully. I am storing that token in session and create a link using createUserAuthorizationUrl(oauthParameters). Then on clicking the link, it redirect me to "Grant Access Page".
Now, even though I grant access, it doesn't show me this page. But, it redirects me to my callback url. However, this seems proper. But, it also doesn't add the entry under My Account. Here, I am storing the oauth_token in session.
When getting redirected, the url of that page contains oauth_token & oauth_verifier, both ! Now, on this callback url, I have a submit button & set action of for to an accessTokenServlet.java. The code of this servlet is as follow :
Now I am sending request to fetch Access Token. My code is :
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthParameters.setOAuthToken(request.getSession().getAttribute("oauth_token").toString());
oauthParameters.setOAuthTokenSecret(request.getSession().getAttribute("oauth_token_secret").toString());
try {
String accessToken = oauthHelper.getAccessToken(oauthParameters);
out.println("Access Token : " + accessToken);
} catch (OAuthException e) {
//System.out.print("Response Status : " + response.getStatus());
out.println("Exception : ");
e.printStackTrace();
return;
}
While clicking on submit button, it prints "Access Token : " & nothing ! No token returns !
I am getting wrong at the stage of authorizing the request token itself. But, I am not getting, what problem got generated ?
The page with the verifier you linked to should only happen if you pass in an oauth_callback of oob — this indicates that you will be moving the verifier out-of-band. I strongly recommend against using oob for anything but debugging. Instead, you should be setting a callback URL and getting the verifier out of the query string.
In the code above, I don't see anything that sets the verifier in the OAuth parameters, so that's likely your problem. You're also not doing much in the way of error handling, and that's a really important piece of the OAuth flow — for example, once you've got it working, try canceling the OAuth process and see how your application handles it.
You will only see the entry in your issued tokens list after you've fully completed the process and obtained an upgraded access token.

Categories