Should a SPA and REST APIs from the same server be two different OAuth clients? - rest

I've been reading and searching for hours with no clear answer to this.
Imagine I have a SPA client hitting REST APIs, and they are served from the same service, e.g. I access my SPA by going to example.com, and the REST API calls that SPA makes are to example.com/api/orders. Do the SPA and the REST API need to be two separate OAuth client registrations?
Conceptually I'm logging into one app, but I can see how they differ. For example, the SPA needs a redirect_url after signing in and is a 'public client', whereas a REST API needs no redirect_url and can be a 'confidential client'. (I can see how it's also more flexible if down the line I want to open up the REST APIs to other consumers, and/or have the SPA call other resource providers directly).
I believe I could get away with one OAuth client registration, but is this an anti-pattern or heavily frowned upon for security reasons? I just want to throw up a simple SPA with some authenticated REST APIs on the same site, and needing two OAuth registrations seems like overkill.

Conceptually, your frontend and the backend should be different OAuth2 clients. But yes, you can get away with one client.
From the security standpoint, it's probably better to have two clients. You can set different security constraints for each - require PKCE for the public client, disable the confidential client requests from outside of your network and such.
I would go with two clients. Even if you don't need anything special for either of them now, it may happen later and it's not much work to create an extra client.
There is another option - having just the backend client and using a session cookie for the frontend authorization.

Related

Is it possible to have two type of auth flow?

Background information: The REST API will be used by a web application and server
We are thinking to have the code flow for the web application and client credential flow for the server part (machine to machine authentication). As tool, we will be using keycloak
But the problem is now that we are not sure if it is possible to have two oauth flow on one REST API.
Is it possible to have two oauth flow for one REST API?
And if it's possible, how can you do it?
This is fine. In both cases the clients will perform OAuth flows using Keycloak, and these can be completely different. Your API needs to knows nothing about how clients authenticated, and in both cases receives a JWT access token.
The two different clients will not always call the same API endpoints. They are likely to use different scopes and claims, and your API authorization design needs to deal with this. The server client will not provide a user identity via a subject claim, whereas the web app will.
The way to cope with these differences is usually to design a ClaimsPrincipal during JWT processing, then apply authorization rules based on the data received within the API's business logic.
In some cases, operations designed for the server client should not be callable from the web app, and vice versa. Scopes and claims will enable you to achieve this.
EXAMPLE API
Maybe have a look at this code sample of mine and the blog post. The key point is that the API performs these steps. If you do the same steps you will be in good shape:
Validates JWT access tokens
Builds a claims principal
Enforces scopes for each operation
Uses the claims principal to apply business authorization rules
My API does some slightly advanced stuff like look up extra claims, which you can ignore. Note that the API doesn't know or care which flow clients used - there could be 5 different flows. The API's job is just to work with scopes and claims.

OAuth2 for REST API with tightly coupled SPA as only client

I'm developing a REST API with a tightly coupled SPA as the only client of the mentioned REST API.
Let's say the SPA is available at myservice.com and api is under myservice.com/api. They're basically one service, just split at code level, and deployed at different root paths.
What I'm using for security right now is OAuth2 with ROPC (username/password) grant type.
Here comes the problem. I keep reading everywhere that ROPC is not secure and should not be used. What should I use then?
My REST API acts as an authorization server but it doesn't have any web interface itself. So any flow involving redirect doesn't really make sense. The SPA and API are so tightly coupled that for an end user they're basically one application. There's no 3rd party.
I could add simple login form to the API available at let's say myservice.com/login. But I'm struggling to see the difference that would make.
Security in this application is very important.
Here are my questions:
Is using ROPC really dangerous in this scenario?
What would be the perfect way for authentication and authorization?
Or maybe OAuth2 is completely redundant without a third party?
Technologies used:
Server: Spring Boot
Is using ROPC really dangerous in this scenario?
No, not really providing:
a) You don't store a user's password - maybe only use it to get the initial access and refresh token - although that could be tricky with an SPA.
b) Your SPA client and the resource API are owned by you, so you don't need the user to consent to specific scoped access for the SPA.
What would be the perfect way for authentication and authorization?
It depends on lots of things. Not enough info to try to answer that. OAuth2.0 (with a probably implemented Authorisation server) is a pretty good way for the example you have here.
Or maybe OAuth2 is completely redundant without a third party?
If other applications will use your API in time then OAuth2.0 is probably a good call. Otherwise you could probably use a more simple solution e.g. session cookies as all sits on same domain.
Answer to this can be taken out from OAuth 2.0 specification (RFC6749) itself. It define when ROPC grant is suitable for,
4.3. Resource Owner Password Credentials Grant
The resource owner password credentials grant type is suitable in
cases where the resource owner has a trust relationship with the
client, such as the device operating system or a highly privileged
application. The authorization server should take special care when
enabling this grant type and only allow it when other flows are not
viabl.
According to your explanation, you have tight coupling with SPA and backend. Also you have both authorization server and resource server built as one. This is completely acceptable implementation.
The authorization server
may be the same server as the resource server or a separate entity.
So what matter now is to clear out why you use OAuth 2.0 in your scenario.
If you are using OAuth 2.0 to obtain tokens, maintain them as defined through OAuth 2.0 specification, then this is completely oaky. But if you are doing this to follow a trend, think twice.
OAuth 2.0 implementation comes with it's own complexity. You have to maintain user identities, maintain tokens and renew them. You are building a complete authorization server by yourself. But this also have some advantages as well.
For example, same authorization server can be used to issue token for future integrations/secondary app. IMO, usage of OAuth 2.0 make integrations easy as it define a protocol for issuing tokens, renew and revoke them.! But in such integration scenario, may be you will require to use a different grant. Still, your API being authorized on token, you only need to worry about how new integration/application obtain tokens. This is better than using authenticated sessions
Going back to your questions,
Q : Is using ROPC really dangerous in this scenario?
As explained, if there is a correct trust relationship between client and authorization server, then it is fine. But be mindful about complexity comes with having a authorization server.
Q : What would be the perfect way for authentication and authorization?
OAuth 2.0 is for authorization. You obtain access token and use them to authorize against your protected APIs. From APIs you do a token validation to detect correct access levels/permissions.
If you want authenticaiton, then you must use OpenID Connect. It is a protocol extended from OAuth 2.0. And allows your application to authenticate the end user based on ID Token. You can use ROPC grant to obtain an ID token.!
Q : Or maybe OAuth2 is completely redundant without a third party?
Not necessarily. It allows you to design your APIs in a modern, standard way. Who know what future hold (again the integration scenario). Following a protocol allows that easy.
Only advice, follow specifications closely. Do not invent your own protocol/adaptation. It makes things harder to maintain.

MIcroservice: Best practise for Authentication

I am looking into using microservice for my application. However the application involves authentication. E.g. there is a service for user to upload their images if they are authenticated. There is also a service for them to write reviews if they are authenticated.
How should i design the microservice to ensure that the user just need to authenticate once to access different services. Should i have a API gateway layer that does the authentication and make this API gateway talk to the different services?
You can do authentication at the gateway layer, if authentication is all you need. If you are interested in authorization, you may have to pass the tokens forward for application to consider it. Also you can do that, if you have trust on other services behind the gateways. That is service 1 is free to call service 2 without authentication.
Also you loose bit of information about the principal, you can however write it back on the request in the gateway while forwarding.
Also another point to consider is JWT, they are lightweight and more importantly could be validated without calling auth server explicitly and it saves you some time specially in microservices. So even if you have to do auth at every service layer you are doing it at minimal cost, some nanoseconds. You can explore that as well.
However final call is based on how strong your security needs are compared to rest. based on that you can take a call. Auth stripping at api gateway saves you code duplication but is less secure as other services can do as they wish.
Same goes for token, you can authenticate without explicit call to auth server but then tokens are valid for some min time and bearer is free to do as they wish once they got the tokens, you cannon invalidate it.
While Anunay's answer is one the most famous solutions, there is another solution I would like to point out. You could use some distributed session management systems to persist sessions on RAM or DISK. As an example, we have authentication module that creates a token and persists it in Redis. While Redis itself can be distributed and it can persist less used data on disk, then it will be a good choice for all microservices to check client tokens with redis.
With this method, there is nothing to do with API gateway. The gateway just passes tokens to microservices. So even in case you are thinking about different authenitcation methods on different services, it will be a good solution. (Although I cant think of a reason for that need right now but I have heard of it)
Inside a session, you can store user Roles and Permissions. That's how you can strict users access to some API's. And for your private API's, you could generate a token with role ADMIN. Then each microservice can call other one with that token so your API's will be safe.
Also you could rapidly invalidate any sessions and store anything you want in those sessions. In our system, spring framework generates a X-AUTH-TOKEN that can be set in headers. The token is pointing to a session key in redis. This works with Cookies too. (and if I'm not wrong, you could even use this method with oAuth and JWT)
In a clean architecture you can create a security module that uses this validation method over API's and add it to every microservice that you want to protect.
There are other options when it comes to session persisting too. Database, LDAP, Redis, Hazelcast ... the choice depends on your need.

RESTful authentication on the web-server

Previously, I did not have to work with HTTP authentication on the server.
But they gave me an assignment.
Quotation:
"We have enough password authentication. While we decided
that there will be enough authentication layer between the client
(AngularJS) and the Web server (RESTful, Jersey)."
Can you help with advice or suggest literature?
REST API resources are stateless. It needed to be secure. On every rest call, authentication must happen to ensure right person access these APIs. It does not mean username and password to be used on the every call.
Industry standard authentication protocols help reduce the effort of securing your API. Custom security protocols can be used, but only under very specific circumstances. This blogs cover few of the major one like OAuth1.a, OAuth2.1 etc.
This link explain Token Based Authentication, every thing you need to start securing your APIs

Why Having a CSRF protection in a REST context doesn't make sense?

Someone to explain please (hopefully with simple words for newbies) why a web application built upon a RESTful API can be CSRF exempt?
I received such assertion after asking: Serializing FormView data in JSON, but honnestly I can't figure out why?
Thanks in advance
CSRF or Cross Site Request Forgery, in layman terms, is meant to allow only selected sources(your own website) to submit data to particular url. It prevents misuse of your functionality by other websites or robots.
Say, I have an url for registration, /registration/, but I don't want to allow external submission of POST data to /registration/. So, I would provide a crsf cookie(depending on host and other stuff) when GET request is issued for /registration/, and ensure that same cookie is provided with POST request. This will ensure that users who have requested the registration form(i.e. genuine web users, not robots), would be able to register. It is not completely full-proof, but ensures some level of security.
Now, We don't use CSRF in API's due to following:-
Technically, CSRF is stored as cookie, since browser is not the intended client of API's, it is of no use.
Secondly, API's are supposed to use specialized client and user authentication, thereby eliminating the need for using any CSRF protection.
Thirdly, Restful api's are supposed to be stateless, therefore the order of API calls should not matter, which is essential for working of CSRF.
Note:-
If you have frontend framework like Angular or intend to use api's on browser too, then it is perfectly ok to use CSRF. In that case you are suppose to write two types of authentication for your apis.
Token Based Authentication - for non-browser clients
Session Authentication - for browser based clients (With csrf)
In this case, any request to api must authenticate with atleast one of the authentication.
According to owasp.org:
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, email, blog, instant message, or program causes a user's Web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.
This is not an issue for REST Web services because either:
1) you usually want your service to be accessible from multiple applications (Mobile app, browser, etc.)
2) you have to provide a direct authentication for each request, so this kind of attack is not applicable for REST services. The authentication is done by your application (let's say javascript) and no directly by your browser (sending the session id), so even if a malicious application redirect the user to your webpage, it cannot automatically trigger your javascript function to perform the request (and the authentication).