Pros/cons security architecture for SPA / Backend - security

I'm not an advanced security developer (what else is new)
Context : I have a monolith using authn/authz mecanism based on a custom JWT stored inside the angular app and refresh frequently. A bit housemade. I'm breaking my monolith one module at a time. And now is about how to handle the security.
I have :
multiple angular apps
multiple Swing apps
multiple back (a big monolith and multiple classic webapplications)
I would like to switch to openid connect. I can :
put a reverse proxy (nginx, kong, ...) with an oidc plugin creating a virtual protected domain for the backends.
From the SPA viewpoint :
Use of code authorization flow with PKCE
When the SPA sends an http request to the RP , the RP check the JWT, validate it, send a 401 if invalidate/missing header.
the SPA redirects the user to the Idp / login page.
Now I'm a bit lost and need to check the Internet :) : I don't know what is the redirect url (the RP or the SPA ? I was assuming only the RP proxy is registered in the Idp)
When the RP forward the original request , the header x-userinfo is set and the backends only read this one.
For back to back communication, we propagaded the x-userinfo header received.
no reverse proxy and each backend checks Authorization Bearer header and redirect to an Authorization server when invalidate or missing. Each back manages the security concerns (validation, redirection, registration).
As you can see I have a lot of misunderstandings. My questions are :
is reverse proxy a good idea ?
is it easier to put a RP with legacy systems (only one header to check ?)
we're putting authz logic inside a RP .... hmmm...
I don't have all the steps inside my head (how the redirections are handled)
when a Swing app (already logged in) wants to redirect the user to a new feature --> open a browser window to an angular app, is there a way to handle the security or do I need to let the angular app handle this (and perhaps force the user to relog into the Idp to obtain a JWT into its cookie/localStorage ?).
Thank you

1a. The redirect URI is the SPA's web origin and should be what you see in the browser. Redirects always occur in the browser (the front channel).
2a. For newer components aim for a zero trust architecture. In OAuth this just means pass a JWT access token to each API. Aim to avoid passing sensitive data used for authorization in headers.
1b. Reverse proxy is an excellent practice for your APIs - as discussed in this IAM Primer. It may be less useful for static web content though, since you may want to deploy that via a content delivery network.
2b. Each app should get its own tokens and redirect the user once - usually a single sign on. In 2021 it is recommended to use secure cookies in SPAs and these cab contain tokens.
Some generic authorization logic can be done in the RP - that is pretty coomon. The real domain specific authorization should be done in APIs though, using scopes and claims.
SUMMARY
Aim to follow best practices for newer components. The Curity links above explain these in a way that cab work for any provider. Hopefully it gives you some useful pointers.

Related

Ways to secure API that do not require authentication, to be called only from one pre-defined consumer

I have currently developed a backend app that has some important functionalities. I want to consume my backend endpoints from my frontend but I want to be sure that only my fronted calls the backend endpoint and no other. Currently anyone that access my web-app can take advantage of the functionalities (I do not require any user registration or authentication).
How can I be safe that my backend is not being called form other possible malicious attackers that may try to steal the functionalities of my backend?
I have read some other posts regarding solutions how to secure a backend app that do not require user authentication but none has a precise and secure way for that. Some say enabling CORS but during my experience I can say that CORS can be manipulated easily with the help of a simple browser plugin. (not speaking about mobile apps that do not consider it at all)
I would really appreciate if I would have some opinions in case of a web-frontend-app, mobile app and other backend systems that would try to call my API and how can I stop them.
Typical front-end authentication would be best (OpenID, ...).
If you want something different, you could check on your backend whether a specific header with a specific token is sent in the query. If it is not then you send back a 401 HTTP code.
This requires that your customers somehow get that token (through some registration process, probably) and then keep it long-term (it can be stored in LocalStorage but can be lost when cleaning up the browser)
OWASP Authentication is a good source of information.

How to prevent others from using my REST API?

I've developed simple REST API using a expressJs. I'm using React as my client side application. So the problem is anyone can see my API endpoints because of react app is in client side. So they will also able to make request and fetch data from my REST API. (May be they will build their own client side apps using my API.) I've seen some question about this and couldn't find any comprehensive answer. How these kind of a security problem should be handled? Is it possible to give the access for API to only my client app? If not how huge brands that using REST API prevent that? (Also I don't have a user authenticating scenario in my product as well. People can just visit and use the website. They don't need to register).
Authentication can be a way but it can be bypassed. Another way is you can create a proxy server which strictly blocks cross origin requests, hence it blocks requests from other domains to make request to your API, and you can make your API call from that proxy server. In this way your API server endpoint will also be not compromised.
If, as you state in your comment, this is about users on your own website being allowed to use your site's API, while disallowing off-site use (e.g. other websites, wget/curl, etc) then you need to make sure to set up proper CORS rules (to disallowed cross-origin use of your API) as well as CSP rules (to prevent user-injected scripts from proxying your API), and you also make sure to only allow API calls from connections that have an active session (so even if you don't want user authentication: use a session managemer so you can tell if someone landed on your site and got a session cookie set before they started calling API endpoints).
Session management and CORS come with express itself (see https://expressjs.com/en/resources/middleware/session.html and https://expressjs.com/en/resources/middleware/cors.html), for CSP, and lots of other security layers like HSTS, XSS filtering, etc, you typically use helmet.

How to implement Security in Rest API developed using Node.JS?

I want to design a SPA which will have Frontend (React) and Backend-Rest API (Node.js, Express, Mongo DB). I am planning to have Single Sign-On in my application where users would be authenticating using MS-Azure AD, where a call would go to Azure AD from Frontend and in return I will get a token for that User which will be stored locally. After that, I want to call my rest API, for multiple GET, POST, PUT operations in the context of current user logged in on UI. Planning to deploy both frontend and backend on different servers so here I have two questions about securing my REST API.
CORS Implementation
User-Authentication on BE
Given the above requirements is it enough to have just CORS implemented or Do I need to again authenticate the User on BE?
Can somebody provide some best practice or experiences? Is there a lack in my “architecture”?
While CORS is definitely a consideration, it isn't Authentication (AuthN) or Authorization (AuthZ) which you need.
Depending on the number of users your application will have, how the back end will scale you might want to look at OAuth2.0 or stick with simpler session based auth but you will need something.
CORS on your back end will limit if a browser running an app on a domain other than yours to call your web services (it wont stop API requests from other tools).
AuthN - Your not logged in - go get logged in and come back to
me.
AuthZ - Controls what your users can and cant do. You might want to
enforce this at the resource level but you absolutely need to within
your business logic.
Further reading https://auth0.com/docs/authorization/concepts/authz-and-authn
Philippe from Pramgmatic web security has a free online course to get you started: https://pragmaticwebsecurity.com/courses/introduction-oauth-oidc.html Its very well paced and should give you some foundational knowledge. (It might let you write off OAuth for this use case but give it a go)
CORS will not perform any user authentication. You need CORS only when your client code is served from another domain than the backend you are talking too. If it is the same server to host static client files and backends REST endpoint, you don't need CORS. If you are unsure, then don't consider CORS at all and see if it works.
But you need authentication to know which user is which.

Secure different types of unsecured applications by a reverse proxy

I'm currently working on a project with complex requirements and I do not feel comfortable with the solution I'm considering.
The main idea is to secure existing applications (which do not include security themselves) without modifying them. These applications are not accessible from outside and will be accessible only through a reverse proxy (OpenResty).
Users do not have access to all applications and the solution to identify users is Keycloak.
The main components are :
An angular portal : the entry point
A reverse proxy that redirect the user on the chosen application
The IAM : Keycloak
All the available application
this schema explain it
The idea is :
The user click sign in on Keycloak and gets back to the portal with an access token (JWT) that contains his roles (application he has access to)
The user click on an application on the portal and he is redirected to the targeted application through the reverse proxy
The reverse proxy check the validity of the token (exp, iss and the roles)
I know this is not a proper way to do some SSO between application, but the requirement here is that the application, that are not secured can't be edited bu have to be protect by an upfront system (the reverse-proxy here)
My question is : ok this will work for the first call, because the user have his JWT token on the portal and hits the application with it the first time, but after when the user will click on a link in this app.. there is no more token. This kind of architecture works well to protect REST API bu for a web application, sounds to me a little incertain.
Generally, you would have reverse proxy server to handle user authentication instead of login to keycloak first.
Flow will be like this:
User access portal.
Portal redirects user to application through reverse proxy.
The reverse proxy will first redirect user to keycloak for
authentication, and build a security session between browser and
reverse proxy server.
The reverse proxy forward request to your application
server.
For all subsequent requests, user always go through reverse proxy server.
Try to use github.com/gambol99/keycloak-proxy. It stores token in the cookie, which is better option for web apps.
!!! Warning: I guess any auth proxy can use only Authorization Code Flow, however Implicit Flow is recommended for Single-Page Application (Angular). It really depends what's your Angular app. Analyze sec. pros and cons first, to be secure.

What's the right OAuth 2.0 flow for a mobile app

I am trying to implement delegated authorization in a Web API for mobile apps using OAuth 2.0. According to specification, the implicit grant flow does not support refresh tokens, which means once an access token is granted for an specific period of time, the user must grant permissions to the app again once the token expires or it is revoked.
I guess this is a good scenario for some javascript code running on a browser as it is mentioned in the specification. I am trying to minimize the times the user must grant permissions to the app to obtain a token, so it looks like the Authorization Code flow is a good option as it supports refresh tokens.
However, this flow seems to rely heavily on a web browser for performing the redirections. I am wondering if this flow is still a good option for a mobile app if a embedded web browser is used. Or should I go with the implicit flow ?
Clarification: Mobile App = Native App
As stated in other comments and a few sources online, implicit seems like a natural fit for mobile apps, however the best solution is not always clear cut (and in fact implicit is not recommended for reasons discussed below).
Native App OAuth2 Best Practises
Whatever approach you choose (there are a few trade offs to consider), you should pay attention to the best practices as outlined here for Native Apps using OAuth2: https://www.rfc-editor.org/rfc/rfc8252
Consider the following options
Implicit
Should I use implicit?
To quote from Section 8.2 https://www.rfc-editor.org/rfc/rfc8252#section-8.2
The OAuth 2.0 implicit grant authorization flow (defined in Section 4.2 of OAuth 2.0 [RFC6749]) generally works with the practice of performing the authorization request in the browser and receiving the authorization response via URI-based inter-app communication.
However, as the implicit flow cannot be protected by PKCE [RFC7636] (which is required in Section 8.1), the use of the Implicit Flow with native apps is NOT RECOMMENDED.
Access tokens granted via the implicit flow also cannot be refreshed without user interaction, making the authorization code grant flow --
which can issue refresh tokens -- the more practical option for native app authorizations that require refreshing of access tokens.
Authorization Code
If you do go with Authorization Code, then one approach would be to proxy through your own web server component which enriches the token requests with the client secret to avoid storing it on the distributed app on devices.
Excerpt below from: https://dev.fitbit.com/docs/oauth2/
The Authorization Code Grant flow is recommended for applications that
have a web service. This flow requires server-to-server communication
using an application's client secret.
Note: Never put your client secret in distributed code, such as apps
downloaded through an app store or client-side JavaScript.
Applications that do not have a web service should use the Implicit
Grant flow.
Conclusion
The final decision should factor in your desired user experience but also your appetite for risk after doing a proper risk assessment of your shortlisted approaches and better understanding the implications.
A great read is here https://auth0.com/blog/oauth-2-best-practices-for-native-apps/
Another one is https://www.oauth.com/oauth2-servers/oauth-native-apps/ which states
The current industry best practice is to use the Authorization Flow
while omitting the client secret, and to use an external user agent to
complete the flow. An external user agent is typically the device’s
native browser, (with a separate security domain from the native app,)
so that the app cannot access the cookie storage or inspect or modify
the page content inside the browser.
PKCE Consideration
You should also consider PKCE which is described here https://www.oauth.com/oauth2-servers/pkce/
Specifically, if you are also implementing the Authorization Server then https://www.oauth.com/oauth2-servers/oauth-native-apps/checklist-server-support-native-apps/ states that you should
Allow clients to register custom URL schemes for their redirect URLs.
Support loopback IP redirect URLs with arbitrary port numbers in order to support desktop apps.
Don’t assume native apps can keep a secret. Require all apps to declare whether they are public or confidential, and only issue client secrets to confidential apps.
Support the PKCE extension, and require that public clients use it.
Attempt to detect when the authorization interface is embedded in a native app’s web view, instead of launched in a system browser, and reject those requests.
Web Views Consideration
There are many examples in the wild using Web Views i.e. an embedded user-agent but this approach should be avoided (especially when the app is not first-party) and in some cases may result in you being banned from using an API as the excerpt below from here demonstrates
Any attempt to embed the OAuth 2.0 authentication page will result in
your application being banned from the Fitbit API.
For security consideration, the OAuth 2.0 authorization page must be
presented in a dedicated browser view. Fitbit users can only confirm
they are authenticating with the genuine Fitbit.com site if they have
the tools provided by the browser, such as the URL bar and Transport
Layer Security (TLS) certificate information.
For native applications, this means the authorization page must open
in the default browser. Native applications can use custom URL schemes
as redirect URIs to redirect the user back from the browser to the
application requesting permission.
iOS applications may use the SFSafariViewController class instead of
app switching to Safari. Use of the WKWebView or UIWebView class is
prohibited.
Android applications may use Chrome Custom Tabs instead of app
switching to the default browser. Use of WebView is prohibited.
To further clarify, here is a quote from this section of a previous draft of the best practise link provided above
Embedded user-agents, commonly implemented with web-views, are an
alternative method for authorizing native apps. They are however
unsafe for use by third-parties by definition. They involve the user
signing in with their full login credentials, only to have them
downscoped to less powerful OAuth credentials.
Even when used by trusted first-party apps, embedded user-agents
violate the principle of least privilege by obtaining more powerful
credentials than they need, potentially increasing the attack surface.
In typical web-view based implementations of embedded user-agents, the
host application can: log every keystroke entered in the form to
capture usernames and passwords; automatically submit forms and bypass
user-consent; copy session cookies and use them to perform
authenticated actions as the user.
Encouraging users to enter credentials in an embedded web-view without
the usual address bar and other identity features that browsers have
makes it impossible for the user to know if they are signing in to the
legitimate site, and even when they are, it trains them that it's OK
to enter credentials without validating the site first.
Aside from the security concerns, web-views do not share the
authentication state with other apps or the system browser, requiring
the user to login for every authorization request and leading to a
poor user experience.
Due to the above, use of embedded user-agents is NOT RECOMMENDED,
except where a trusted first-party app acts as the external user-
agent for other apps, or provides single sign-on for multiple first-
party apps.
Authorization servers SHOULD consider taking steps to detect and block
logins via embedded user-agents that are not their own, where
possible.
Some interesting points are also raised here: https://security.stackexchange.com/questions/179756/why-are-developers-using-embedded-user-agents-for-3rd-party-auth-what-are-the-a
Unfortunately, I don't think there is a clear answer to this question. However, here are the options that I've identified:
If it is ok to ask the user for his/her credentials, then use the Resource Owner Password Credentials. However, this may not be possible for some reasons, namely
Usability or security policies forbid the insertion of the password directly at the app
The authentication process is delegated on an external Identity Provider and must be performed via an HTTP redirect-based flow (e.g. OpenID, SAMLP or WS-Federation)
If usage of a browser based flow is required, then use the Authorization Code Flow. Here, the definition of the redirect_uri is a major challenge, for which there are the following options:
Use the technique described in https://developers.google.com/accounts/docs/OAuth2InstalledApp, where a special redirect_uri (e.g. urn:ietf:wg:oauth:2.0:oob) signals the authorization endpoint to show the authorization code instead of redirecting back to the client app. The user can manually copy this code or the app can try to obtain it from the HTML document title.
Use a localhost server at the device (the port management may not be easy).
Use a custom URI scheme (e.g. myapp://...) that when dereferenced triggers a registered "handler" (the details depend on the mobile platform).
If available, use a special "web view", such as the WebAuthenticationBroker on Windows 8, to control and access the HTTP redirect responses.
Hope this helps
Pedro
TL;DR: Use Authorization Code Grant with PKCE
1. Implicit Grant Type
The implicit grant type is quite popular with mobile apps. But it was not meant to be used like this. There are security concerns around the redirect. Justin Richer states:
The problem comes when you realize that unlike with a remote server
URL, there is no reliable way to ensure that the binding between a
given redirect URI and a specific mobile application is honored. Any
app on the device can try to insert itself into the redirection
process and cause it to serve the redirect URI. And guess what: if
you’ve used the implicit flow in your native application, then you
just handed the attacker your access token. There’s no recovery from
that point — they’ve got the token and they can use it.
And together with the fact, that it does not let you refresh the access token, better avoid it.
2. Authorization Code Grant Type
The authorization code grant requires a client secret. But you should not store sensitive information in the source code of your mobile app. People can extract them. To not expose the client secret, you have to run a server as a middleman as Facebook writes:
We recommend that App Access Tokens should only be used directly from
your app's servers in order to provide the best security. For native
apps, we suggest that the app communicates with your own server and
the server then makes the API requests to Facebook using the App
Access Token.
Not an ideal solution but there is new, a better way to do OAuth on mobile devices: Proof Key for Code Exchange
3. Authorization Code Grant Type with PKCE (Proof Key for Code Exchange)
Out of the limitations, a new technique was created that let you use the Authorization Code without a client secret. You can read the full RFC 7636 or this short introduction.
PKCE (RFC 7636) is a technique to secure public clients that don't use
a client secret.
It is primarily used by native and mobile apps, but the technique can
be applied to any public client as well. It requires additional
support by the authorization server, so it is only supported on
certain providers.
from https://oauth.net/2/pkce/
Using a webview in your mobile application should be an affordable way to implement OAuth2.0 protocol on Android platform.
As for redirect_uri field, I think http://localhost is a good choice and you don't have to port a HTTP server inside your application, because you can override the implementation of onPageStarted function in the WebViewClient class and stop loading the web page from http://localhost after you check the url parameter.
public void onPageStarted(final WebView webView, final String url,
final Bitmap favicon) {}
The smoothest user experience for authentication, and the easiest to implement is to embed a webview in your app. Process the responses received by the webview from the authentication point and detect error (user cancel) or approval (and extract token from url query parameters).
And I think you can actually do that in all platforms. I have successfully made this work for the following: ios, android, mac, windows store 8.1 apps, windows phone 8.1 app. I did this for the following services: dropbox, google drive, onedrive, box, basecamp. For the non-windows platforms, I was using Xamarin which supposedly does not expose the entire platform specific APIs, yet it did expose enough for making this possible. So it is a pretty accessible solution, even from a cross platform perspective, and you don't have to worry about the ui of the authentication form.

Resources