How to protect REST API when using AJAX? - ajax

There are SNS application with 2 servers. Web backend server and REST API server.
The web server allows user login/logout with username/password, and show user information
The REST API server provides APIs like /topics, /comments, it should be stateless without session
The REST API will serve other web applications
There are some potential solutions, but neither is security.
Base Auth, the browser hold the username/password
Token with expiry timestamp, the problem is user could stay on the page until token expires
So, is there a way to protect the REST API when calling it from AJAX?

If I have understood your problem correctly I may suggest you use the Token solution. In order to maintain security you may generate new token on every request (& send it to client in response), which should be used to make next request, and disable token if it is once used or has expired.
Sorry, I meant to mention it as a comment, but I don't have enough reputation.

Related

How to access a secured API in the frontend?

There is a lot of good content on the internet that explains how to secure a Spring API with Keycloak: Create a Client that represents the API Service in Keycloak and use a link like the one below to get the access and refresh token:
<Domain>/auth/realms/<realm>/protocol/openid-connect/auth/{some parameters}
This yields both tokens. So far so good.
Now, however, I am not sure how the flow for the frontend accessing the API should look like.
Should the frontend directly access this endpoint and, therefore, obtain the access and refresh token? That would mean that the API can only have the access-type public because there is no way to store the client (the API) secret securely.
Or should there be a third server that somehow stores the refresh token for each user, that the user can call if his access token is no longer valid. This server would then use the client's refresh token (and the client secret that could be stored securely, since it would be in the backend) to get a new access token from Keycloak and would forward it to the user.
I guess the main question that I am asking is, whether the client/user should get the refresh token.
If one needs to implement a logic according to the second option, I would be interested in a link or description of how something like this can be done in Spring.
I think, in either case you need to use the Authorization Code Flow. The implicit flow, which was recommended for SPAs (frontends without a backend server) in former versions of OAuth2 must not be used anymore.
The best option is to have a backend server, so the user retrieves the auth code via redirection and the backend server exchanges this auth code with the access and refresh tokens (and keep them without forwarding them to the frontend).
If there is no backend in place and your frontend needs to retrieve and hold the tokens directly, I would recommend to use the Authorization Code Flow with a public client and the PKCE extension (which - put simply - ensures that the entity asking for the auth code is the same as the entity asking for the tokens and that the auth code was not stolen and used by a foreign entity). There are several sources with more detailed explanations, which might help you, for example: https://auth0.com/docs/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce
Hope this helps you with your architectural considerations.

Securing web app and api using OpenID Connect

I don't want to roll my own security anymore and am looking at using OpenID Connect with my c# API and AngularJS app. I can get all that to work just fine. However, my brain cannot seem to understand how to secure my API correctly for both use cases:
Use Case 1: AngularJS SPA
My AngularJS app connects to my API and sends a bearer token identifying the user and includes user claims. This one is easy and there is tons of documentation on it.
Use Case 2: API to API
Some customers want to access my API directly instead of going through my AngularJS app. In this case, I thought I could use a Client ID/Secret for toen-based authentication which is great except then I know nothing about the user that's using the client id/secret. There could be 10 users using the same custom API that is calling my API. How do I get user info via the API call? I've seen others use API keys that they then lookup the user and create a JWT but I thought there might be an easier way. Any ideas?
The whole point of API to API authentication is that there is no user context. Or well, the user in that case is the machine trying to access your API. You would then need to design your authorization logic around that and implement scope based permissions. Alternatively, your options are to use api keys as you mentioned or if you want OAuth protocol with user context in the api to api scenario - then ResourceOwnerCredentials flow is an option.
API to API communcation
You can use Client Credentials Grant defined through OAuth 2.0. This won't require you to have end user credentials. Now this won't be OpenID Connect. OpenID Connect require the involvement of an end user and bound to authentication. OAuth 2.0 on the other hand is about authorization, checking whether the entity can access the resource.
With Client Credential Grant, your identity server will issue tokens for a specific client. So one of your API becomes the client (resource consumer). From request handling API endpoint, you can accept valid tokens and respond back with resource.
If you require fine grained access control from request handling API, you will require to use token introspection to identify to whom this token was issued. In this case, it will be identification of specific client identity and execute a logic on top of it. You can check the token introspection response to identify such details.
Alternatively, access tokens can be come in form of a JWT. If this is the case, they can be considered as self contained tokens so validation is straightforward.

Google Oauth2: Refreshing id_token on the client side

I'm developing an angularjs web app.
To access server side api, I need to add an id_token header and
I receive an id_token, by using https://accounts.google.com/o/oauth2/auth endpoint.
The crux of the matter is this - the id_token has an expiration date. Before accessing server API, I need to make sure the id_token is not expired yet, but if it is, the obvious choice would be to refresh it.
Is there any way I can refresh the id_token?
I know I could change access_type to offline, and receive a refresh_token, but it does seem pretty weird to ask for an offline access, when basically in my case user interacts with the server only at the moment when he actually using the web app online.
Forget all about refresh tokens and offline access. This method is only applicable for server and desktop apps. To have a refresh token present in the browser would be a massive security hole.
If you read the docs for the Google JS OAuth library, you'll see that it's easy to get a new access token once the current one expires. See gapi.auth.authorize() and note the comment for immediate=true. NB this method is deprecated, although it works. Absolutely everything you need to is at https://developers.google.com/api-client-library/javascript/reference/referencedocs
When the id_token expires, the client requests new tokens from the
server, so that the user does not need to authorise again.
From IMPLEMENTING A SILENT TOKEN RENEW IN ANGULAR FOR THE OPENID CONNECT IMPLICIT FLOW

How can I protect my WebAPI from abuse and avoid sharing API keys?

I have a Web API written in C# and hosted in Azure with Azure API Management (AAM) sitting in front of that API and throttling requests.
The clients that call the API will be javascript based and will be calling on behalf of anonymous end users. For example, the home page of a web site might call our API via javascript to present information to an end user without asking them to login.
AAM ensures that callers to the API have a valid API key. There is the potential for this key to be copied and abused though if someone grabs it from the publicly visible source.
Is it possible to use OAuth2 to obtain a JWT Access Token without human intervention and for this to be exposed on the client?
OAuth2 can issue expiring JSON Web Tokens which would lower the risk of token theft, but I'm struggling to get this going without any human intervention.
OAuth2 is mostly about end user initiated authorisation but IdentityServer3 seems to have a Hybrid approach. Could I use this Hybrid approach to get the remote web server to request a token by sending the API key from server to server first and then outputting the JWT in the web page for use by the client side script?
This would then hide the API key and only show a JWT that is of use for a few minutes.
AAM can integrate with OAuth2 and inspects JWT Access Tokens, but I don't think it understands this Hybrid flow (it may not need to as we won't be asking for user logins).
Or should I just give up and rate limit requests only?
If you can generate these hybrid JWT keys without user intervention then API Management can validate them and use one of the claims as a key for doing rate limiting. Normally rate limiting is done based on API Management subscription keys, but the new advanced rate limiting policies allow you rate limit based on any expression.
I'm not familiar with how the IdentityServer hybrid mode keys work, but usually if there is non-interactive login, then there is some kind of secret that needs to be protected. This is always a challenge when running code on the client.
The API Management HTTP API does have a method to regenerate keys. You could use this to implement your own token expiry mechanism to limit the impact of key theft.

Securing REST calls made by JavaScript from an unsecured page

We have a web-based application in which we are not requiring end users to login. The application uses Ajax to make calls to REST services hosted on the same server. Besides this application, we want to make sure that if any other applications / agents call the REST service they get denied.
What is the simplest way to secure a REST API like this? My guess is that we would include some sort of security token and make the call through HTTPS. However I'm not clear how the Ajax application would create/obtain/encrypt the token and generally what the lifecycle looks like.
I would rather do this outside of Spring Security or OAuth if possible. I have also read that sending username and password over SSL is enough for authentication. In this case, the app would have a "username" and password and it would send it with every request to the REST service. But how would it keep that information secret if the client is just HTML and javascript in the browser?
Thanks.
In general this is impossible. Someone could just do view source on your javascript, read the token, then do whatever they want.
https is not necessary here. For the token, probably the easiest is to set a cookie when they download the javascript from the server, then that cookie will also be transmitted with any AJAX requests.
This is not really secure - anyone can just see what the cookie is and use it, but it's the best you can do.

Resources