I'm writing an application that sends requests to the Twitter API. One part of the flow requires a redirect to the Twitter login page. After the user has logged in, a request is sent back to the callback url with information I need to continue the flow. The thing is, after logging in, my application pops up with the relevant information in the url bar. So, for example the url would look like this:
{http://localhost:9000/?oauth_token=KlQrT7YoFC2j3wAVGK57JRRI5h6LFI08H1zkhm8uEo&oauth_verifier=dU1H8D1no1wmKNRdpecHDrWegTQm4dvI15rnUblqxM}
I need the information after the {'http://localhost:9000'} so my question is, how do I get that?
The only information I can find on HTTP Request is making them, very little about receiving them. And even the stuff I did find on receiving them doesn't cover the issue I'm having. I imagine a solution to this problem could be very useful seeing as it goes to the core of any application that wants to implement sign in with Twitter.
Any help would be greatly appreciated.
Create a controller which serves /, example routes file
GET / Twitter.authorize
And then in the controller you can use the parameters:
public static void authorize(String oauth_token, String oauth_verifier) {
.... do something ....
}
Related
I have a problem with Vertx oauth2.
I followed this tutorial http://vertx.io/docs/vertx-web/java/#_oauth2authhandler_handler:
OAuth2Auth authProvider = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions()
.setClientID("CLIENT_ID")
.setClientSecret("CLIENT_SECRET")
.setSite("https://github.com/login")
.setTokenPath("/oauth/access_token")
.setAuthorizationPath("/oauth/authorize"));
// create a oauth2 handler on our domain: "http://localhost:8080"
OAuth2AuthHandler oauth2 = OAuth2AuthHandler.create(authProvider, "http://localhost:8080");
// setup the callback handler for receiving the GitHub callback
oauth2.setupCallback(router.get("/callback"));
// protect everything under /protected
router.route("/protected/*").handler(oauth2);
// mount some handler under the protected zone
router.route("/protected/somepage").handler(rc -> {
rc.response().end("Welcome to the protected resource!");
});
// welcome page
router.get("/").handler(ctx -> {
ctx.response().putHeader("content-type", "text/html").end("Hello<br>Protected by Github");
});
The ideas is to have in the protected folder all the webpages that requires auth.
When I want to access to protected webpage I get redirected to the microsoft login site and after the login I get redirected to my callback.
What I donĀ“t understand is how to handle the callback now?
I get something like this as response:
https://localhost:8080/callback?code=AAABAAA...km1IgAA&session_state=....
How I understood (https://blog.mastykarz.nl/building-applications-office-365-apis-any-platform/) I need to extract somehow the code and the session-state and send back with a post to:
https://login.microsoftonline.com/common/oauth2/token
in order to get the token.
But I did not understand how this can be done with Vertx.
Any help? How to extract the code and session and send back to Microsoft?
I found some tutorials here: https://github.com/vert-x3/vertx-auth/blob/master/vertx-auth-oauth2/src/main/java/examples/AuthOAuth2Examples.java but did not help me.
I am doing this with Azure authentication (in tutorial is written Github but i changed all this to Microsoft).
Are you behind a proxy? The callback handler sends a request to the provider from the application and not from a browser. For me this froze the whole application. You can set the proxy with OAuth2ClientOptions given to the OAuth2Auth.create
As mentioned in the official vert.x-web document, the handling of the auth flow (including access token request to microsoft) is handled by OAuth2AuthHandler:
The OAuth2AuthHandler will setup a proper callback OAuth2 handler so the user does not need to deal with validation of the authority server response.
This being said, there is no need for application to manually handle it. Instead of using example from vertx-auth, try this one instead which actually uses OAuth2AuthHandler.
I have an idea to make something pretty sweet but I'm not sure if it's possible. Here is an example of a very basic ajax function that I might use to establish a connection a server...
function getFakePage(userId)
{
var ajaxObject, path, params;
ajaxObject = getAjaxObject();
params = "?userId=" + userId
path = getInternalPath() + "someServlet" + params;
ajaxObject.open("GET", path, true);
ajaxObject.send();
// On ready state change stuff here
}
So let's say I have a URL like this...
https://localhost:8443/Instride/user/1/admin
And I wanted to use javascript to redirect the user to this this URL. Normally I would just do this...
window.location = "https://localhost:8443/Instride/user/1/admin";
But my idea is to create a javascript (no js frameworks please) function that could combine the ajax code with the window.location code. Basically what I would like to accomplish is to create a connection with the server via ajax, send a servlet on that server the url I would like the user to be redirected to, and then redirect the user to that URL. So that for however long it takes the user to connect to my server from wherever they are in the world they see a loading icon instead of a blank white page.
So to clarify exactly what I am trying to accomplish; I do not want to put window.location within the success of my ajax function (because that would be encompass two round trips), and I do not want to return a huge chunk of HTML for the requested resource and add it to the page. I want to establish a connection to the server with ajax, send a servlet the URL the user wants to go to, and then somehow override the ajax function to redirect that user. Is this possible?
And I know some of you might think this is stupid but it's not when you're talking about overseas users with slow dial up connections staring at white pages. If it's possible, I'd love to hear some insight. Thank you very much!
First, let me say that the best solution is finding what is causing the slowness and fixing it.
Now as to your question, yes you could do it. You could even shoehorn it onto an existing application. But it wouldn't be pretty. And it comes with it's own set of problems. But here are the steps:
Browser calls ajax cache service requesting "somepage.html"
Browser loads loading icon
Server creates somepage.html and caches it in a temporary cache, (ehcache or other library would be good, probably with file backing for the cache depending on size)
Server responds to ajax request with ID for cached page
Browser now redirects to "somepage.html?cacheId={cacheId}" where the id is from the ajax call.
Server uses a filter to see if any cache can be served up for the page instead of the actual page, thus speeding up the request.
Having said that, it would be better to just have the new page load quickly with a loading icon while it did any of the heavy lifting through ajax.
You can't do an AJAX request and a location change in one. If you want to do only one request you have to choose one of those methods. ie. return some data and replace content on your current page, or load a completely new page.
It doesn't make any sense to want to want to do both. What you could want is stateful URLs; where your URL matches the content displayed, even if that content comes from an AJAX request. In that case an easy solution is the use the # part of the URL which you can change freely (window.location.hash). Some modern browsers support changing the whole URL without causing the page to reload. I've used # with great success myself.
My Servlet response type is html and my response contains a hyperlink to another web site.So, now i want to capture the information about whether the user clicked the link or not? and also calculate the total clicks? i am using Tomcat 7 as a server.
Is this possible in setting response header (302 or 404)?...
Please Guide me to get out of this issue?
Yes, you can use a 302: instead of providing the link to the other website, you provide a link to your own servlet, do your accounting and then send back a redirection (301/302) http status with the other web-site URL in the response Location header.
This maybe a bit simplistic though, since the user will leave your original page (is this what you want ?) and search engines may not like this if your web app is public.
I think right now you are redirecting the request(link for another website) at client side.In this approach your server cannot get the information about the click.
What you can do create a servlet and call this servlet on click now this servlet is responsible to redirect the request to another website. Add an static integer counter and increment this when servlet call each time.
Use the method setStatus():-
setStatus(HttpServletResponse.SC_FOUND);
or
setStatus(HttpServletResponse.SC_NOT_FOUND);
I want to access a full rest service with basic http auth running.
However there is no way to for the javascript browser client to suppress the authenticate box when a wrong credential is provided.
I thought about different methods to solve this problem
someone suggested to remove the WWW-Authenticate Header with a filter (i dont think this is a clean approach)
i could rewrite my app to not use Basic Http Auth at all (i think this is too much trouble)
i could write a proxy that talks to my regular service
I like the last approach the best.
I keep my regular Rest Interface, but also have the option to use this interface with clients that are not that flexible.
Furthermore I can later proxy Http Requests unsupported by some browsers.
The idea is to have a /api/proxy/{request} path that proxies to /api/{request} and returns a Facebook-Graph-like JSON query { data: {data}, error: {error}}
This is the stub of the Proxy class
#Path("proxy")
public class ProxyResource {
#GET()
#Path("{url: [a-zA-Z/]*}")
public String get(#Context Request request, #PathParam("url") String url) {
// remove proxy/ from path
// resend request
// verify result
}
}
I can access the Request (which seems to be a ContainerRequest). How can I modify the request without building it from scratch to resend it.
Edit: when somebody knows a better approach i am delighted to hear about it.
As I started to digg deeper into this, i found out that not the 401 was the problem. The www-authenticate header sent back from the server caused the browser to open the login box.
If somebody is interested I've written a little nodejs proxy to remove a www-authenticate from all server requests.
https://gist.github.com/ebb9a5052575b0a3f41f
As this is not the answer to my original question I will leave it open.
I'm working on a web app that uses Jersey. I'm trying to implement a get-after-post sort of thing using a URIBuilder and a seeOther response. The aim is to redirect to the same URI the browser is already on, but to force a GET. It works a bit like this:
Request comes in via PUT
PUT request processed
SeeOther response returned
What should happen is that the browser picks up the 303 See Other and performs a GET on the URI it receives. Unfortunately, what's happening is that it performs a PUT on the URI instead (as far as I can tell) and the PUT sends it back to Step 1. above, causing a redirection loop.
Any ideas what's going wrong here?
private Response giveSeeOther(){
/*Get the base URI builder*/
final UriBuilder uriBuilder = m_uriInfo.getBaseUriBuilder();
/* Some stuff to create the URI */
final Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("uid", getUid());
final URI redirectUri = uriBuilder.path(SomeObject.class).
path(SomeObject.class, "get").
buildFromMap(parameterMap);
/* See Other (303) */
return Response.seeOther(redirectUri).build();}
That's the code for the see other method. I'm not sure what other code you might want to see, but let me know.
You need to use a 301 HTTP response code instead.
By using 303, your POST request is maintained, and redirected accordingly. By using 301, your request is "Moved permanently" via GET.
For other readers who might wonder why someone wants to do this, it's to prevent the user from submitting their POST data more than once by using the "Reload" function of their web browser (which users with "rotten communications" problems often do) to reload the "thank you" page that may not have loaded completely.
Hint: When you redirect in this manner, if you're not using cookies to ensure information gets to your "thank you" page, then you'll need to add one or more parameters to your request in the same way a regular GET form will. For example, if the order ID number is 82838, you can pass it along to your "thank you" page like this:
http://www.example.com/order/thank-you.pl?orderid=82838
There are obvious potential security issues with this which are easily resolved by having your "thank you" page code check that the order ID actually belongs to the currently logged in user before it displays the order status (I assume you wish to include order status information on that "thank you" page -- in this case, it's also nice to include a "Refresh" button {or link} for the user to check up on the order status if it's something that progresses in the short term over a number of steps).
I hope that's helpful to you.