I'm trying to understand this example project which uses Google's OAuth library to let users login with their Google account.
Specifically, I'm trying to understand the relationship between Oauth2AuthorizationCodeServlet.java and Oauth2CallbackServlet.java. I know that Google's OAuth 2.0 library uses them to kick off the authorization flow and to handle the result after the user logs in, and I've read through the documentation for both abstract classes, but I'm wondering why both classes need to repeat the same logic?
Both classes define getUserId() functions which return the same value.
Both classes define initializeFlow() functions which return the same value.
Both classes define getRedirectUri() functions which return the same value.
The code works fine, and I can see that the functions are called in this order:
Oauth2AuthorizationCodeServlet#getUserId()
Oauth2AuthorizationCodeServlet#initializeFlow()
Oauth2AuthorizationCodeServlet#getRedirectUri()
Oauth2CallbackServlet#initializeFlow()
Oauth2CallbackServlet#getRedirectUrl()
Oauth2CallbackServlet#getUserId()
Oauth2CallbackServlet#onSuccess()
But I'm wondering why the repeated functions in Oauth2CallbackServlet are necessary.
Why can't Google's OAuth 2.0 library use the values returned by the first class? Would it ever make sense for the corresponding functions to return different values? For example, would it ever make sense for their getRedirectUrl() functions to return different URLs?
Here is simplified diagram of google oauth login flow.
No 1. here represents Oauth2AuthorizationCodeServlet
No 2. here represents Oauth2CallbackServlet
Those are two different servlets, responsible for separate parts of login flow. 1 - redirects user to google login form with some url params like redirect url.
2 - handles callback after user finished with login, this servlet can access user info from google, perform actions on user behalf in google etc.
To answer your questions:
Why can't Google's OAuth 2.0 library use the values returned by the first class?
Those are two separate servlets - it would be incorrect to perform communication between two separate servlets.
Would it ever make sense for the corresponding functions to return different values? For example, would it ever make sense for their getRedirectUrl() functions to return different URLs?
In common scenario i don't think it makes sense to return different values from those servlets, but maybe some exotic scenario exists, where you have to support multiple google login callback urls for different use cases.
Related
I’m fairly new to REST API and working on a product where client X interacts with n number of servers (Y1, Y2,…Yn) to retrieve different type of data from backend, using POST requests.
Now I also want to retrieve some metadata related to each server (file names, project name etc.) for our internal use-case in client X. Note: This should be a separate request.
How should I implement this using Rest?
Can I use OPTIONS method for this?
I tried implementing this with GET method but not sure if it’s best approach.
Since you are going to retrieve information the GET is the most appropriate. POST instead should be used to 'insert' fresh new datas. I would suggest to take a look at the meaning of all HTTP verbs (POST,GET,PUT,PATCH,DELETE) in order to understand them.
I'm working on a web application using React on the frontend and Java on the backend. From the frontend, I call different resources from the backend, where I have various classes providing #GET methods.
For every method, I'm always using the same check to determine if the user is authorized based on their session ID. That's a very repetitive way to accomplish this. This is especially true when creating a new #GET method, as I have to always remember to add this isUserAuthorized check.
My first thought was using an abstract class for the resources to centralize some of the code, but here I'd still have to add the check to each method.
Is there a way I can implement the authorization check for all HTTP requests, without needing to repeat this code?
I have been working on a GWT application, which is a variation of an issue tracking system. There are some projects, which have some tickes(tasks or issues) assigned to some users. One of the requirements is to provide the administrator with an option to give access to a certain non-user person, to a specific task of a specific project. This can be a read or read/write access.
So, the question is, what are some best practices to achieve this, especially in a GWT application? Are there some specific protocols, or frameworks etc to be used.
My understanding is to generate a unique(non-guessable) url token, map it to the ticket(task, issue). And also, map the token to an access type(read, read/write). Then, load the mapped ticket, with the right access type.
But, i am wondering if there is a out of the box solution to this?
AFAIK there is no ready-solution in GWT.
Basically you will create a history token (i.e. http://MyGWTApp.com/tasks/#!SOME_LONG_UID).
When the user navigates to this URL, you have to check on the backend if the UID is valid. You can do this by using either RPC, RequestBuilder, or rf. Conveniently you can return the access type (red/write) back to the client.
With the access type you can then disable some UI interface elements.
Some things to keep in mind:
For each task/action that goes to the backend you have to check if the UID allows the access pattern (= never trust the client). So you also have to send along the UID with each request.
You can also have to make sure on the backend that when the anonymous users can only carry out the tasks (read/write) that are allowed (= whitelist).
Suppose I have a set of JAX-RS locators and sublocators, like the following:
#Path("/users")
public class UserListResource {
#Path("/{id}")
public UserResource getCustomer(#PathParam("id") int id) {
// Find and return user object
}
}
public class UserResource {
#GET
public String get() {...}
}
For example, a UserResource object with the ID 5 would have the path "/users/5". In my system, I have several different resources.
Now the question is: How can the server figure out the path of a given resource? Can I do this programmatically via some JAX-RS API or do I have to implement code that uses reflection? (I know how to do the latter, but would prefer the other approach.)
At the point when I need to know the path, I do not have a request object at all. For example, I have a timer which does some background processing, then changes some entities in the domain model, then informs all clients about the changed entities (including their paths).
I know that within the scope of a request, I can inject a UriInfo object that provides this, but I need to know the path in advance (to inform clients of a change that did not necessarily happen through the JAX-RS resource).
I don't want to repeat the path information in another place, and I also don't want to have a set of path fragment constants for each resource type (in this case "/users" and "/{id}").
As I read your question, you need to build a URI knowing only the resource class and the id parameter.
It can be done using the UriBuilder class as in:
UriBuilder builder=UriBuilder.fromResource(UserListResource.class);
URI uri=builder.path(UserListResource.class,"getCustomer").build(5);
It uses reflection under the hood, so it is not so easy to refactor, but it is all it is available at the moment.
Overall, be aware that something sounds rather strange with the architecture of your application. It's hard to put a finger on, but the pattern of questions you are asking is raising a number of red flags about how you're going about this. Be aware that if you are seeking to create a RESTful API to your application that you may need to stop, take a few steps back, and rethink what you are trying to do.
To your explicit questions…
Now the question is: How can the server figure out the path of a given resource? Can I do this programmatically via some JAX-RS API or do I have to implement code that uses reflection? (I know how to do the latter, but would prefer the other approach.)
The server knows the path, as that's always supplied by the user and is used to navigate through the collection of resource classes that make up your application. If you need a UriInfo instance for a particular call, you should inject it as part of that specific call:
#GET
public String get(#Context UriInfo info) {...}
Any information required from the outer context (e.g., what the resource's ID is) is best passed in during construction. You can reparse it out of the URL (obtainable from the UriInfo) again, but that's probably the wrong approach.
Otherwise, if you're doing something much more complex then you need to be more specific in your question.
At the point when I need to know the path, I do not have a request object at all. For example, I have a timer which does some background processing, then changes some entities in the domain model, then informs all clients about the changed entities (including their paths).
I know that within the scope of a request, I can inject a UriInfo object that provides this, but I need to know the path in advance (to inform clients of a change that did not necessarily happen through the JAX-RS resource).
How are you going to have the clients be informed? There's normally no mechanism to push messages from the server to the clients, and clients are typically firewalled so that they can't directly host a service.
Theoretically, you could associate (explicitly, by URL) each resource with its own RSS feed to which a client could listen to if they chose. You wouldn't be able to force clients to listen, but you could give them the option to do so. If you go this route, you don't need to know the UriInfo “ahead of time” as the location information will be present at key times (i.e., at resource creation) and afterwards you're just referring to something that you have control over.
But that's just one way to do it and it adds a lot of complexity; you'd only do it if it was critical to your application. It's often simpler to just have clients poll from time to time. (Note that some sorts of modifications are inherently very destructive; particularly altering the ID or deleting the resource. Don't expect things to cope smoothly with those.)
I don't want to repeat the path information in another place, and I also don't want to have a set of path fragment constants for each resource type (in this case "/users" and "/{id}").
Tough. Repeating information in multiple places, provided you draw it consistently from a single source, is a common practice. There's nothing actually wrong with it.
As I understand your question, you want to know the path as the request is coming in but before it hits your resource; are you open to using Servlet Filters?
JAX-RS specific filters are only supported in 2.0
For the record: after I had posted the question, I thought about our architecture a bit more and came to the conclusion that sending URLS is not as useful as I thought. The application has to know some details about the application structure anyway:
Continuing the example above: even if the client did not know the URL pattern for individual users, it must assume that there is a list of users and know its URL; it also has hard-coded knowledge what dialog to display for editing a user etc.
So all in all, attempting to tell the client (most) URLs it needs is not worth the effort. Instead, we decided to go with a custom API definition file which includes data about the resource contents and their URL scheme. This file is used to generate the following:
the server-side resource classes with the correct JAX-RS annotations
a URL scheme specification document for other developers to code against
classes for our own client (including the URL know how, e.g. user with ID 5 has the URL ...), so we don't have to worry about inconsistencies between our client and server.
This approach has the following advantages:
The need for the server to figure out the URLs from the annotations vanishes, as the client can now do that on its own once it receives a notification that includes the object ID.
We don't have to worry about inconsistencies between our client and the server, as all information is drawn from a single source.
We have one source for the API definition under version control which can be used to verify backwards compatibility with older releases.
Note:
I would probably not claim that the resulting API stays "faithful" to the idea of RESTful webservices, but it works for us and the elements that it borrows from "actual" REST architectural style should make the API clearer and easier to learn than a traditional contract-first webservice.
I am writing a web application using JSP/Spring MVC and would need to customize the UI based on the customer using it. I would need to hide/show certain sections of the screen, hide show certain labels and their text boxes and also modify labels based on different customers. Currently we are controlling the hide/show in the JSPs by elements and divs based on the logged in customer. For example:
if (customer= "A")
show this
else
hide this
The code gets cluttered and the JSP will get bloated as we add more customers.
Another alternative I have thought is split a page into sections and control the sections in the same way, but might end up in code repetition accross the JSPs.
For example
if (customer = "A")
jsp:include headerA.jsp
else
jsp:include genericheader.jsp
Another alternative would be to write different JSPs and route based on the client.
Is there a better way to handle this kind of situations. Can someone suggest the best practices to implement such a solution?
Thanks.
A UI that chooses what to do for each user can't possibly scale beyond your users A and B. You need a role-based authentication and authorization system.
Since you're already using Spring, I'd recommend looking at Spring Security and its role based capabilities. There are tags that can help you.
Another way to look at it is that role-based logic like this does not belong in tags. I'd recommend putting it in controllers and let them assemble pages for you.
Another possibility is something like SiteMesh, which allows you to create composite views.
One more: jQuery was born to manipulate the DOM. Use it along with CSS.
First thing it should be based on Role and not based on customer, and each customer will have certain role. It may possible that many customers will have same role and screen access and UI.
Based on role, you can use Spring Secutiry for Authentication and Authorization.
If you need to use Layout differently as per customer role, preferably you should use some Layout Manager such as Tiles, SiteMesh etc.
or use portlets for different login views to different customers
You just stated if person A logs in from one store, vs person B logs in from another. Hate to say it, but that's a role, no matter how you want to spin it, this is related to user authorization.
In terms of how you want to implement it, you could do a variety of things, you could intercept the login request and set a session variable which prepends a string to determine the correct view (i.e. when user a logs in you get customerA, vs customerB, so when rendering the view you'd retrieve the value and render "customerA/index" vs. "customerB/index", etc.
You could also determine the person's roles within the controller and render the appropriate view, although this couples your user roles to your controller logic, which wouldn't be recommended in my opinion.
If this app is going to have a lot of different backends, I'd recommend portlets that way you can write a new backend for each app, rather than bloating your web application with every new store backend.
Those are just a couple ways, hope this helps.