How to take a redirection URL - java

I have a problem with redirection, in my work I have to make a connection to a URL that automatically go to another URL at this point it takes the credential (username and password) and redirect to a URL that contains a parameter which need me. How can I take this parameter?
To be precise, I have to do this:
Embed a Web browser with the URL https://graph.facebook.com/oauth/authorize with your client_id and the type set to user_agent. Since your application is embedding a small window, you can trigger a compact "popup" version of the authorization dialog with the display parameter:
graph.facebook.com/oauth/authorize?
client_id=...&
redirect_uri=www.facebook.com/connect/login_success.html&
type=user_agent&
display=popup
After the user authorizes your application, we redirect the user back to www.facebook.com/connect/login_success.html with the access token in the URL fragment: www.facebook.com/connect/login_success.html#access_token=...&expires_in=... Intercept the redirect above and read the access token out of the URL. Use the access token to fetch data from the Graph API on behalf of the user:
graph.facebook.com/me?access_token=....
I need access_token.

you can use apache http components httpclient to do this,
it will automatically follow redirects
HttpClient client=new HttpClient();
GetMethod get=new GetMethod("graph.facebook.com/oauth/authorize?client_id=...& redirect_uri=www.facebook.com/connect/login_success.html&type=user_agent&display=popup");
int status=client.exectueMethod(get);
Then you will have the information you need in the Location header of the response which you can access by using:
String location=get.getResponseHeader("location").getValue();
and parse the location-header for the url fragment you want.
hope that helped

Related

Spring OAuth2 and query string parameters in redirect_uri

So we've a spring-boot based oauth2 server.
One of our applications relying on this server tries to initiate an auth request using the following url:
https://oauth2server/oauth/authorize?response_type=code&grant_type=authorization_code&client_id=myClient&redirect_uri=http%3A%2F%2Fapplicationserver%2Flogin%3Fparameter%3Dvalue
The user enters credentials, approves the app, and is redirected back to the application-server via the redirect_uri with a code:
http://applicationserver/login?parameter=value&code=tokenCode
When the application-server then calls the oauth2 resource api (oath/token) it gets RedirectMismatchException("Redirect URI mismatch.") because the approved redirect doesn't contain the query string parameters, rather only http://applicationserver/login
How can we set a certain url prefix to be an approved redirect uri while ignoring query string parameters? or are we doing something inherently wrong?
Thanks!!
If I understand it correctly your intention is to send data with the initial authorize request which should be returned when redirecting back to the application.
A library I am using currently provides the feature that an additional state can be stored together with the nonce in the state parameter like:
state = nonce + nonceStateSeparator + customState;
The state parameter is described as:
An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in Section 10.12.

How can I access a 'Web App' built in Google Apps Script from Android?

I can successfully access Google Drive and Spreadsheet functionality from my application.
So I have an authorised instance of com.google.api.client.auth.oauth2.Credential.
Now I wish to execute a Google Apps Script that is deployed as a 'Web App'. This will also require authentication to run. This script runs in the browser if I hit the endpoint and am authenticated.
Here's some psuedo code :
String url = "https://script.google.com/a/macros/mycompany.com/s/xxxx/dev";
GenericUrl webAppEndPoint = new GenericUrl(url);
final HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(currentCredential);
// Do POST for service
String requestBody = URLEncoder.encode("{\"name\":\"John Smith\",\"company\":\"Virginia Company\",\"pdf\":\""+getPdfBase64()+"\"}", "UTF-8");
HttpRequest postRequest =requestFactory.buildPostRequest(new GenericUrl(url), ByteArrayContent.fromString(null, requestBody));
postRequest.getHeaders().setAccept("application/json");
postRequest.setFollowRedirects(true);
postRequest.setLoggingEnabled(true);
HttpResponse postResponse = postRequest.execute();
If I run the code I get the following error : com.google.api.client.http.HttpResponseException: HttpResponseException 405 Method Not Allowed
UPDATE : So - originally i was POSTing to the wrong URL ( i'd copied the redirected URL from a browser instead of the script URL )
The POST is now successful ( authentication included ) using the above code, but it still doesn't handle the GET redirect after submission. I can work with this now but it would be good to be able to get a response from the server.
I think that com.google.api.client.http.HttpRequest doesn't handle authenticated POST redirects properly.
Your pseudocode isn’t very illuminating; to really see what’s going on you’d need to show the actual HTTP traffic. I should say though that a 302 redirect to a specified redict_uri is a normal part of the OAuth 2 authentication flow.
1) you cant call an apps script with authentication. You need to publish it as anonymous access as a contentService.
2)you are also calling the wrong url. Call the service url not the redirected one that you get in the browser.

How to detect the redirect to retrieve access_token via java

I'm starting to use facebook Graph API and I'm going to retrieve an access token with some simple HTTP requests via java.
Following https://developers.facebook.com/docs/authentication/
I created a new app but I don't have a domain so
I make an HTTP request to
www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&
redirect_uri=https://www.facebook.com/connect/login_success.html
for a server-side flow, and I suppose to get redirect to a success page with a code in the URL. Then I would use this code make another HTTP request to
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
and finally get my access token.
I used both java.net.HttpURLConnection and org.apache.http.HttpResponse,
but, in both cases, executing the first call I get as response the HTML of a Facebook login page.
If I use this HTML to create a webpage and then I simply click on the Login button (without inserting username and password) I get the success page with the code!
In the HTML the field submit of the button Login is empty and I can't retrieve redirect URLs... I can just read an alternate link in the <meta> tag which generate an auth_token (what is it? It is very different wrt an normal access_token...).
So what I ask is:
it is possible to detect the hidden redirect in some way just
using java.net.HttpURLConnection or
org.apache.http.HttpResponse?
if yes, how is the mechanism? Is it related to the auth_token?
if no, is it possible with other libraries? (I used also restfb,
but they seems to require an access token inserted "by hand" as an
arg, and I also saw facebook-java-api but it seems old).
Also if I'm logged in Facebook, executing the first HTTP call via Java I get as response the HTML of a Facebook login page.
Using HTML to create a webpage and then I simply click on the Login button (without inserting username and password) I get the success.htm page with the code parameter in the URL.
If I use the original URL directly in my browser I can directly obtain the success.htm page without passages in the middle.
So I suppose the problem is in the management of cookies: in Java (executed in Eclipse) I cannot access my browser's cookies.
I tried to redirect to use a Servlet but I get the error about the domain:
ServletURL is not a Facebook domain or a "site URL" registered for my app (actually I did't set a site URL for my app... and that's the problem core).
In any case here
http://developers.facebook.com/docs/authentication/
in the section App types > Desktop apps they say:
[...] After the user authorizes your app [I allowed everything], we
redirect the user back to the redirect_uri with the access token in
the URI fragment: [...]
Detect this redirect and then read the access token out of the URI
using whatever mechanisms provided by your framework of choice. [...]
So I think that it is still possible to detect this redirect via Java. How?
If you do not have a domain yet I recommend you using localhost as a domain. That way you can test it on your local web server / local app.
Using HttpURLConnection works fine.
This is how we do it.
Redirect to:
"https://graph.facebook.com/oauth/authorize?" +
"client_id=" + clientId + "&" +
"redirect_uri=" + URLEncoder.encode(returnUrl, "utf-8")
// After redirect to the return url do the following:
//Make a http request to
"https://graph.facebook.com/oauth/access_token?client_id=" +
"client_id=" + clientId + "&" +
"redirect_uri=" + URLEncoder.encode(returnUrl, "utf-8") + "&"+
"client_secret=" + clientSecret + "&"+
"code=" + request.getParameter("code");
This will return an access token which you can query facebook with

Programmatically using j_security_check

I have page like localhost:7001/MyServlet. I am making a http connection request from like below
String url = "http://localhost:7001/MyServlet"
PostMethod method = new PostMethod(url);
HttpClient client = new HttpClient();
However "MyServlet" is protected by j_security_check. So when I am making my connection , getting redirected to login page.
How to get authenticated and access my url , in one HttpConnection
Note: I use apache common httpclient
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
I doubt you can log in and call the server in a single request, unless HTTP BASIC authentication is enabled. While I do not know the details of HTTPClient's API yet, basically you will need to track a session using cookies; POST your login to /j_security_check; then access the servlet. (The same basic process works for /j_acegi_security_check if using ACEGI Security.)
A nasty wrinkle in Tomcat is that just posting right away to /j_security_check gives a 400 "bad request"; its authenticator is rather finicky about state transitions and was clearly not designed with programmatic clients in mind. You need to first access /loginEntry (you can throw away the response other than session cookies); then post your login information to /j_security_check; then follow the resulting redirect (back to /loginEntry I think) which will actually store your new login information; finally post to the desired servlet! NetBeans #5c3cb7fb60fe shows this in action logging in to a Hudson server using Tomcat's container authentication.

Servlets encodeRedirectURL

I'm trying to get an OAuth implementation running on a servlet for Twitter. I'm having trouble with redirecting the user to the Twitter authentication page. When I get the callback, it's returned to a servlet but the session is different since the request comes from Twitter and not my webapp.
I tried using encodeRedirectURL to get the session to persist to the outside site but that doesn't work. Need help!
You have to add the session ID as jsessionid fragment of callback URL. Twitter has to callback to http://example.com/callbackservlet;jsessionid=1E6FEC0D14D044541DD84D2D013D29ED (note: the jsessionid value is here just an example).
The HttpServletResponse#encodeRedirectURL() (and encodeURL()) won't encode the URL when the client already supports cookies. You need to hard-encode it yourself.
String url = "http://example.com/callbackservlet";
String encodedURL = url + ";jsessionid=" + request.getSession().getId();

Categories

Resources