UserService, OAuth, and AJAX in App Engine - java

I'm running a webapp that checks if a user is logged in with UserService, then shows them their homepage if they are, or redirects them to a login screen if not. Once on the page, I would like to be able to update specific portions using AJAX when they click certain elements. Now, I have already written a REST API in the same GAE project using Cloud Endpoints that gets all the information I want, and so in the spirit of DRY I would rather use my own API than write new servlets to handle these requests.
The problem is that I need to generate an OAuth token in order to access the API. I can easily do this from the Google API JavaScript Client Library, but then my user needs to re-authenticate for the rest API, which is not only bad from a UX perspective, but more importantly exposes my client id in the page's javascript and passes a token through HTTP (non-SSL) headers.
The only option I see is to write a servlet for each request and have duplicate work. But conceptually, I'm already logged in to Google, so I should just be able to access the API. How does one usually go about this? Am I thinking about it all wrong?

UserService and OAuth are two different authentication (and authorisation) mechanisms and you can not combine them.
If you do need OAuth to access some of the APIs than also use server side OAuth. This way you can access APIs and replace UserService all in one go.

Related

How do I hide a Spring Boot "GET" API request from the public in a browser?

As the question states, my goal is to hide a GET route in Spring Boot from being accessed from the public. I originally took a CORS approach, but that doesn't solve the actual view problem. Pretty much anyone could go to, say... https://my-api-url.com/employee/all and see a JSON record of all employees in my database.
END GOAL: I only want my front-end to have access to my API for displaying that information to an authorized user who is signed in, but I do NOT want just anyone to have access to the API. CORS policy can handle the ajax requests, but it doesn't seem like I can stop the overall viewing of the GET url.
How can I solve this problem?
You can use OAuth to register clients(frontend/postman/whatever you are using to test the API) that can access your resource server, but it might be overkill. For now, if you worry someone can view your API by typing it in the address bar(if that is your question) then you can allow access for authenticated users only.
If you want to restrict usage and make it inconvenient for abusers to call your API, you can issue a token on page load (CSRF token) and require that token to be present in the request to the API - that way the API will be callable from a browser that initiated a page load.
You can refer this link https://security.stackexchange.com/questions/246434/how-can-i-ensure-my-api-is-only-called-by-my-client
If your frontend is currently handling authentication, i‘d suggest moving to Springs Authenticationserice. That way you could prevent unauthenticated users from accessing that specific API endpoint.

How Should I Add Authorisation In My REST API If I Use Azure APIM?

I am planning on hosting my REST API in a VM in a VNET where the only point of entry is via Azure API Management.
I have multiple back ends so the API Management will route to a different backend base url depending on the group the user is in and the backend will also return different data depending on the user making the call.
Since the Azure API Management can handle authorisation, JWT validation and setting headers etc what type of authorisation code should I put in my REST API application?
Should I try to validate the JWT again in my Java code or just parse the headers?
i.e. is it safe to code it as a public API and trust that the headers have been set correctly by API Management?
Or should I make a call to Azure Active Directory from the Spring controller every time to validate that the user does actually exist in the specified group and that the group specified is the one expected for this backend?
If so, how would I do that from Java and how would I inject an offline version when running locally?
Since your API will be inside a VNET it'll be protected as it is. But, there is really no reason to just have it open. The more layers of protection you can add the better your chances to whistand a potential attack.
So see whatever is most convenient to you. You can rely on APIM doing user authentication and authorization and avoid doing that in your backend API. But it would be a good idea to check if call made to your backend API is coming from APIM, and you can do that by sending credentials from APIM. The best option here would be client certificates: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-mutual-certificates
But you can also send basic credentials: https://learn.microsoft.com/en-us/azure/api-management/api-management-authentication-policies#Basic

Exposing a web site through web services

I know what I am asking is somehow weird. There is a web application (which we don't have access to its source code), and we want to expose a few of its features as web services.
I was thinking to use something like Selenium WebDriver, so I simulate web clicks on the application according to the web service request.
I want to know whether this is a better solution or pattern to do this.
I shall mention that the application is written using Java, Spring MVC (it is not SPA) and Spring Security. And there is a CAS server providing SSO.
There are multiple ways to implement it. In my opinion Selenium/PhantomJS is not the best option as if the web is properly designed, you can interact with it only using the provided HTML or even some API rather than needing all the CSS, and execute the javascript async requests. As your page is not SPA it's quite likely that an "API" already exists in form of GET/POST requests and you might be lucky enough that there's no CSRF protection.
First of all, you need to solve the authentication against the CAS. There are multiple types of authentication in oAuth, but you should get an API token that enables you access to the application. This token should be added in form of HTTP Header or Cookie in every single request. Ideally this token shouldn't expire, otherwise you'll need to implement a re-authentication logic in your app.
Once the authentication part is resolved, you'll need quite a lot of patience, open the target website with the web inspector of your preferred web browser and go to the Network panel and execute the actions that you want to run programmatically. There you'll find your request with all the headers and content and the response.
That's what you need to code. There are plenty of libraries to achieve that in Java. You can have a look at Jsop if you need to parse HTML, but to run plain GET/POST requests, go for RestTemplate (in Spring) or JAX-RS/Jersey 2 Client.
You might consider implementing a cache layer to increase performance if the result of the query is maintained over the time, or you can assume that in, let's say 5 minutes, the response will be the same to the same query.
You can create your app in your favourite language/framework. I'd recommend to start with SpringBoot + MVC + DevTools. That'd contain all you need + Jsoup if you need to parse some HTML. Later on you can add the cache provider if needed.
We do something similar to access web banking on behalf of a user, scrape his account data and obtain a credit score. In most cases, we have managed to reverse-engineer mobile apps and sniff traffic to use undocumented APIs. In others, we have to fall back to web scraping.
You can have two other types of applications to scrape:
Data is essentially the same for any user, like product listings in Amazon
Data is specific to each user, like in a banking app.
In the firs case, you could have your scraper running and populating a local database and use your local data to provide the web service. In the later case, you cannot do that and you need to scrape the site on user's request.
I understand from your explanation that you are in this later case.
When web scraping you can find really difficult web apps:
Some may require you to send data from previous requests to the next
Others render most data on the client with JavaScript
If any of these two is your case, Selenium will make your implementation easier though not performant.
Implementing the first without selenium will require you to do lots of trial an error to get the thing working because you will be simulating the requests and you will need to know what data is expected from the client. Whereas if you use selenium you will be executing the same interactions that you do with the browser and hence sending the expected data.
Implementing the second case requires your scraper to support JavaScript. AFAIK best support is provided by selenium. HtmlUnit claims to provide fair support, and I think JSoup provides no support to JavaScript.
Finally, if your solution takes too much time you can mitigate the problem providing your web service with a notification mechanism, similar to Webhooks or Resthooks:
A client of your web service would make a request for data providing a URI they would like to get notified when the results are ready.
Your service would respond immediatly with an id of the request and start scraping the necessary info in the background.
If you use skinny payload model, when the scraping is done, you store the response in your data store with an id identifying the original request. This response will be exposed as a resource.
You would execute an HTTPPOST on the URI provided by the client. In the body of the request you would add the URI of the response resource.
The client can now GET the response resource and because the request and response have the same id, the client can correlate both.
Selenium isn't a best way to consume webservices. Selenium is preferably an automation tool largely used for testing the applications.
Assuming the services are already developed, the first thing we need to do is authenticate user request.
This can be done by adding a HttpHeader with key as "Authorization" and value as "Basic "+ Base64Encode(username+":"+password)
If the user is valid (Users login credentials match with credentials in server) then generate a unique token, store the token in server by mapping with the user Id and
set the same token in the response header or create a cookie containing token.
By doing this we can avoid validating credentials for the following requests form the same user by just looking for the token in the response header or cookie.
If the services are designed to chcek login every time the "Authorization" header needs to be set in request every time when the request is made.
I think it is a lot of overhead using a webdriver but it depends on what you really want to achieve. With the info you provided I would rather go with a restTemplate implementation sending the appropriate http messages to the existing webapp, wrap it with a nice #service layer and build your web service (rest or soap) on top of it.
The authentication is a matter of configuration, you can pack this in a microservice with #EnableOAuth2Sso and your restTemplate bean, thanks to spring boot, will handle the underlining auth part for you.
May be overkill..... But RPA? http://windowsitpro.com/scripting/review-automation-anywhere-enterprise

Same Form based authentication for two applications Using Spring Security

We have an existing legacy web application(Servlet+jsp+spring+hibernate) and we are going to develop some new features of the application using a new stack (angularjs+Spring mvc). Currently suggested approach is to register a new servlet and develop the new features in the same codebase, so the authenticated users will have access to the new functionality we develop in the system. Is there a better way of doing this as a two different web applications (without SSO) ? Can two web applications be secured under the same form based authentication settings ?
I think architecture and security usability is very important before dive into something.
If both apps use same login, then I assume the newer application is more likely a service oriented application. Ex: RESTful
Authorization may be an issue. Ex: Legacy app is used by user set A, new one is used by both user set A and B.
Otherwise you can use a shared database for example MongoDB to store your login info i.e token.
When you log in, return that token and use for the other service via angular client. When you log out remove any token for that user session. You may also need to concern about token expiration.
However you have to refactor your legacy system in someway to use a token. If it is not possible, you can use session sharing which is handled by the the container if the the both apps are running under same container. Ex: Tomcat. But now it may very hard to integrate with a native mobile app if you are hoping to do so.
Sharing session data between contexts in Tomcat
From the point of Spring security and angularjs, authenticating via form is just an http POST with content type being application/x-www-form-urlencoded. One difference is the response to a non authenticated request, for one response should be a http redirect (jsp, to a login page), one with an unauthorized code (for angularjs). That could be handled with a custom AuthenticationFailureHandler or on the client side. A similar difference may occur for the successful login redirection.

Calling a REST web service secured with Spring Security from Android

I'm hosting a REST web service in a Grails application, using Spring Security, i.e.:
#Secured(['IS_AUTHENTICATED_REMEMBERED'])
def save = {
println "Save Ride REST WebMethod called"
}
I'm calling it from an Android app. (Calling the unsecured service works just fine.)
To call the service, I'm manually building up a request (HttpUriRequest) and executing it with an HttpClient.
I'm wondering what the best practices are, and how to implement them... Specifically, should I:
Perform a login once, to retrieve a JSESSION_ID, then add a header containing it into the HttpUriRequest for each subsequent request?
Or (not sure how I would even do this) include the login and password directly on each request, foregoing the cookie/server-side session
I think I can get option 1 working, but am not sure if Spring Security permits (2), if that's the way to go... Thanks!
--also, there isn't any library I'm missing that would do all this for me is there? :)
Spring security does support both basic authentication and form based authentication (embedding the username/password in the URL).
A REST service is generally authenticated on each and every request, not normally by a session. The default spring security authentication (assuming you're on 3.x) should look for basic authentication parameters or form parameters (j_username and j_password) (in the form http://you.com/rest_service?j_username=xyz&j_password=abc).
Manually tacking the j_username/j_password onto the URL, adding them as post parameters (I believe), or setting the basic authentication username/password should all work to authenticate a REST service against the default Spring Security interceptors, right out of the box.
I will admit that I haven't tried this on REST services, though I do clearly recall reading exactly this in the docs as I did the same for basic page logins on spring security recently. Disclaimer over.
I think you can use a login-once-and-get-a-token method that's similar to how oauth works.
sending username and password across the network outside of secured channel(https/ssl) is a terrible idea. anyone on the network can sniff your request package and see the clear text password.
on the other hand, if you use a token method, since the token string is randomly generated, even the token is compromised, the worst case is someone can use the token accessing your REST API.
another solution is going through ssl tunnel(HTTPS). i have actually done a comparison and result shows: 80 requests/min(https) vs 300 requests/min(http)

Categories

Resources