Handling client-side authorization with Firebase - javascript

I'm building a client that uses Firebase, the Firebase JavaScript SDK, the Firebase Authentication service, and the Real Time Database for persistence.
Following a number of different sources, I have the authentication piece working well, but I'm finding limited options for authorization for what I'd consider an efficient solution.
What I want to do is attach a single key/value of role: 'admin' to the user's auth record so that I can conduct both authentication and authorization with only one client-based call to the Firebase backend.
I've read about attaching custom claims to the Firebase Authentication record, but I've only seen folks using the Firebase Admin library (backend) to both set the token and parse the token. I'm trying to not add additional calls through Firebase functions or a custom Express server, if I can help it.
Adding a separate User profile record to the RTDB is easy, and I can store the auth data there. However, this will always require a simultaneous call for Authentication and Authorization, which, again, seems very inefficient and excludes secure offline use of the client (if roles change on the RTDB).
It also seems inefficient to make a client-based call for authentication, then fire a mandatory second client-based call to retrieve authorization data from a Firebase function (or any other backend service) that can implement the Firebase admin library.
Main question: Is there a way with JavaScript to achieve the goal of setting/retrieving both authentication and authorization data from the Firebase Authentication service with a single request to the backend and processing on the client?

The two options you've given are the idiomatic approaches for custom roles.
If you embed the role into the user's token as a custom claim, you'll get it in the authentication request. Since this is an operation that elevates permissions, it should be done in a trusted environment, such as a server you control, Cloud Functions, or (if infrequent enough) from your development machine.
If you don't want to do that, and want to store it in the database, you'll need an extra request. The overhead of that call is usually not a performance problem.
A combination of the two is also possible: identify the initial "system administrator" UID manually, and then use that in your database security rules to allow the to grant additional rights to other users. But that will also have the roles in the database.
Instead of finding reasons to not use these idiomatic approaches, I recommend implementing one and seeing if your concerns surface in practice.

Related

How does the firebase authentication and realtime application database secure itself?

I'm curious about this from a general development perspective of how to secure access to online resources. We initialize our webapp with the following firebase configuration parameters:
apikey
authdomain
projectid
databaseurl
messagesenderid
How does the server use these to ensure that the requests are valid? Mainly why can't someone else just fish these parameters out of the application and then create another "Evil" application that uses the same parameters for "Evil".
"Evil" would include creating a different app with the same credentials fished up of the real app, signing up users against the same credentials contained in the real app using the plain email / password signup form, and then once the users are signed in doing even more "Evil".
Also simple node express js application and we wanted to secure access to it using the above parameters how would that work from an application request lifecycle perspective?
1) Express receives request
2) Express checks that ...
Lastly is any of this part of how openid-connect works? In other words is it following the openid-connect spec at all or is a custom based security solution built specifically for firebase?
These configuration parameters do nothing more than identify your Firebase project on the various servers. They are not in any way meant as an authentication/authorization mechanism.
See my answers here:
my answer to Is it safe to expose Firebase apiKey to the public?
and to How to restrict Firebase data modification?
and Kato's excellent answer to How to prevent other access to my firebase
You'll note that most of these point to Firebase Authentication for authenticating users, and then server-side security rules for authorizing their access. With both of these in place, it doesn't really matter anymore what code performs the access. If the user is authenticated against the same back-end, and the data access adheres to your server-side security rules, it means it follows the rules you set, no matter whose code it is.

Is there anyway to secure API keys in React JS, even though it's on the client side?

Is there anyway to secure an API key when using it on a React javascript file ? For example;
emailjs.init("API_KEY");
You may want to check how Google Firebase does pure client-side authentication: https://firebase.google.com/products/auth/
Edited:
This general introduction to Authentication using API-keys, OAuth etc (source: codecademy course on bulding web-apps) may help understand what API keys are meant for and why it should't be necessary to secure them. The reason is that there are other ways to deal with secret information, as described in this article.
Authentication
INTRODUCTION
Authentication is the process used by applications to determine and confirm identities of users. It ensures that the correct content is shown to users. More importantly, it ensures that incorrect content is secured and unavailable to unauthorized users.
In this article, we’ll discuss a few of the common design patterns for these interactions. You’ll need to have some basic understanding of HTTP requests, since these methods all use HTTP requests to exchange information.
PASSWORD AUTHENTICATION
The most common implementation of authentication requires a user to input their username or email and a password. The application's server then checks the supplied credentials to determine if the user exists and if the supplied password is correct. If the credentials are correct, the user is logged in and able to use the application as thatthe user.
Typically, upon a successful login, the application will respond with an authentication token (or auth token) for the client to use for additional HTTP requests. This token is then stored on the user's computer, preventing the need for users to continuously log in.
This token generally expires after a certain amount of time, ensuring the correct user is using the application over time as well.
API KEYS
While it is common to think of authentication as the interaction between a human user and an application, sometimes the user is another application.
Many apps expose interfaces to their information in the form of an API (application program interface). For example, the Spotify API provides endpoints for almost all of its functionality. This allows applications to fetch data from the Spotify music catalog and manage user’s playlists and saved music.
Since these external requests could overwhelm a service and also access user information, they need to be secured using authentication.
The most basic pattern for API access from another application is using an API key.
Public APIs usually provide a developer portal where you can register your application and generate a corresponding API key. This key is then unique to your application. When your application makes a request, this key is sent along with it. The API can then verify that your application is allowed access and provide the correct response based on the permission level of your application.
The API can track what type and frequency of requests each application is making. This data can be used to throttle requests from a specific application to a pre-defined level of service. This prevents applications from spamming an endpoint or abusing user data, since the API can easily block that application's API key and prevent further malicious use of the API by that application.
OAUTH
For many applications, a generic developer-level API key is not sufficient. As mentioned earlier, APIs sometimes have the ability to provide access to user-level data. However, most services only provide this private data if the user enables it.
For example, Facebook doesn't want Tinder to access all of their users' data, just the users who have opted in to allowing the sharing of data to better help them find a match in their area.
A basic approach to this problem might be to have the user provide their login credentials to the intermediary application, but this is not very secure and would give full access to the requesting application, when the requesting application might only need a very limited set of privileges to function.
OAuth defines a more elegant approach to this problem. It was developed in November 2006 by lead Twitter developer Blaine Cook and version 1.0 was published in April 2010.
OAuth is an open standard and is commonly used to grant permission for applications to access user information without forcing users to give away their passwords.
An open standard is a publicly available definition of how some functionality should work. However, the standard does not actually build out that functionality.
As a result, each API is required to implement their own version of OAuth and therefore may have a slightly different implementation or flow. However, they're all based around the same OAuth specification.
This can make using a new OAuth API a little more frustrating. However, with time you will begin noticing the similarities between API authentication flows and be able to use them in your applications with increasing ease. Below is a summary of the standard OAuth flow.
GENERIC OAUTH FLOW
Many applications implementing OAuth will first ask the user to select which service they would like to use for credentials:
Login with Google, Facebook or Twitter
After selecting the service, the user will be redirected to the service to login. This login confirms the user’s identity and typically provides the user with a list of permissions the originating application is attempting to gain on the user’s account.
If the user confirms they want to allow this access, they will be redirected back to the original site, along with an access token. This access token is then saved by the originating application.
Like a developer API key, this access token will be included on requests by the application to prove that the user has granted access and enable access to the appropriate content for that user. When a user returns to the application, the token will be retrieved and they will not have to re-authenticate.
OAUTH 2
Since OAuth evolved out of Twitter, there were important use cases not originally considered as part of the specification. Eventually, this led to the creation of a new version of the specification, called OAuth 2.
Among other improvements, OAuth 2 allows for different authentication flows depending on the specific application requesting access and the level of access being requested.
OAuth 2 is still an open standard, so each API will have its own flow based on its particular implementation. Below, we’ll discuss a few of the common OAuth 2 flows and how they are used.
CLIENT CREDENTIALS GRANT
Sometimes an application will not need access to user information but may implement the added security and consistency of the OAuth 2 specification. This type of grant is used to access application-level data (similar to the developer API key above) and the end user does not participate in this flow.
Instead of an API key, a client ID and a client secret (strings provided to the application when it was authorized to use the API) are exchanged for an access token (and sometimes a refresh token). We will discuss refresh tokens in more depth later.
This flow is similar to our first example, where an email and password were exchanged for an authentication token.
It is essential to ensure the client secret does not become public information, just like a password. As a result, developers should be careful not to accidentally commit this information to a public git repository. Additionally, to ensure integrity of the secret key, it should not be exposed on the client-side and all requests containing it should be sent server-side.
Similar to the previously-mentioned keys, the returned access token is included on requests to identify the client making the requests and is subject to API restrictions.
This access token is often short-lived, expiring frequently. Upon expiration, a new access token can be obtained by re-sending the client credentials or, preferably, a refresh token.
Refresh tokens are an important feature of the OAuth 2 updates, encouraging access tokens to expire often and, as a result, be continuously changed (in the original OAuth specification, access tokens could last for time periods in the range of years). When a refresh token is used to generate a new access token, it typically expires any previous access tokens.
AUTHORIZATION CODE GRANT
This flow is one of the most common implementations of OAuth and will look familiar if you’ve ever signed into a web application with Google or Facebook. It is similar to the OAuth flow described earlier with an added step linking the requesting application to the authentication.
A user is redirected to the authenticating site, verifies the application requesting access and permissions, and is redirected back to the referring site with an authorization code.
The requesting application then takes this code and submits it to the authenticating API, along with the application’s client ID and client secret to receive an access token and a refresh token. This access token and refresh token are then used in the same manner as the previous flow.
To avoid exposing the client ID and secret, this step of the flow should be done on the server side of the requesting application.
Since tokens are tied both to users and requesting applications, the API has a great deal of control over limiting access based on user behavior, application behavior, or both.
IMPLICIT GRANT
The previous two methods cause the client secret key to be exposed, so they need to be handled server-side. Some applications may need to access an OAuth API but don't have the necessary server-side capabilities to keep this information secure.
The Implicit Grant OAuth flow was designed for this very use case. This flow prompts the user through similar authorization steps as the Authorization Code flow, but does not involve the exchange of the client secret.
The result of this interaction is an access token, and typically no refresh token. The access token is then used by application to make additional requests to the service, but is not sent to the server side of the requesting application.
This flow allows applications to use OAuth APIs without fear of potentially exposing long-term access to a user or application's information.
CONCLUSION
OAuth provides powerful access to a diverse set of sites and information. By using it correctly, you can reduce sign-up friction and enrich user experience in your applications.
No, if it's out in public, it is public.
But you can set up a server that takes care of the communication in the background so you key would be kept secret.
In the case of Firebase it seams, that there shouldn't be a security risk though. See this answer here

Authentication in SPA using Auth0 and clients node.js server

Background
I have two apps:
Angular2 Single Page Application
Node.JS with express
I'd like to authenticate and authorize users logging into Angular2 app, by consuming API exposed by express server. I'd like to use Auth0 as my IDP. I want the whole app (client + server) to be made-to-measure.
At the same time:
I don't want to use Auth0 Lock
I don't want to use refreshes and redirects (for fine UX and simplified flow)
I don't want to ship auth0.js library to Angular2 app (to minimize payload and client-side code complexity).
I would like to keep auth data returned by server in localStorage (as opposed to passport.js setting cookies and refreshing)
Preferably, I wouldn't want to set up database for these purposes, although it's possible.
Proposed architecture
Red arrows indicate authentication flow.
5 is a generic API request.
Actual question(s)
Are there any contraindications to using such architecture?
How do I achieve it and what do I need to pass through each of 4 requests/responses? (the simplest scenario and prerequisites)?
Are there any resources which will help me get better understanding of OAuth and authentication in general, for beginners in this field?
Q1
Given that OAuth2 uses HTTP redirects for a significant part of the functionalities it specifies, going with an architecture such as that one and imposing that many constraints will reduce the number of possibilities you can leverage. Besides that, I don't see any major problems.
Q2
Given you don't want to use redirects the OAuth2 flow that you need to use is the resource owner password grant (ROPC), mostly because of the four flows that OAuth2 provides it's the only one that would meet your requirements.
❌ Authorization code grant (redirect-based)
❌ Implicit grant (redirect-based)
✅ Resource owner password grant
❌ Client credentials grant (aimed at client applications that want to access an API on behalf of themselves and not of an end-user)
In request 1 and 2 you pass the username and password credentials, first to your own server and then to the authorization server. In requests 3 and 4 the access token resulting from a successful user authentication is delivered to the AngularJS application that can store it in localStorage for later use.
This meets your exact requirements, but it's not the most common architecture in use. Normally, the SPA would use the implicit grant to get the access token. Given this grant is optimised exactly for this purpose it can be implemented with good UX characteristics, however, it would indeed make use of redirects.
Q3
The OAuth2 specification itself is not that hard on the eyes and it would be the best resource I would recommend. For a more high-level and quick intro into the topic I would also recommend https://auth0.com/docs/protocols/oauth2.

How to set up session token between JS and PHP API?

I have designed a simple HTML/CSS and JS/jQuery application, and now it's the moment of authentication integration. On the server side, I have done a REST API which allows clients to get some data. But, now I want to authenticate each request with access and/or session token.
I read many websites to find agreements or advice to establish security between the client (JS) and the REST API (PHP), but unfortunately I found nothing or not interesting.
So I ask you to enlighten me (if you want) to know what to do, what to implement, conventions, etc.
What I read:
Designing a Secure REST (Web) API without OAuth
Token Based Authentication for Single Page Apps (SPAs)
I cannot post more links according to my reputation...
Just give me advice, ways how to store private token (RSA) or access/session token for API.
Don't hesitate to give your reaction, and tell me if I'm not exact or something else.
You need to use a token-based authentication for your REST API. JWTs are the best in this particular case.
Why Use JSON Web Tokens?
Tokens are stateless. The token is self-contained and contains all the information it needs for authentication. This is great for scalability as it frees your server from having to store session state.
JWTs can be generated from anywhere. Token generation is decoupled from token verification allowing you the option to handle the signing of tokens on a separate server or even through a different company such us Auth0.
JWTs have fine-grained access control. Within the token payload you can easily specify user roles and permissions as well as resources that the user can access.
This will be your typical authentication flow process:
A user signs up/logs in, during the login process, you generate a JSON web token from the server and return it to the client. Since you are using PHP, you can use this library for the generation and signing of the token.
Store the JWT returned to the client on the browser Web Storage(local/session storage). It can also be stored in a cookie.
For subsequent HTTP requests from the client to the server, you send the token via headers/query, then the server validates the token. If it's valid, the user is authenticated otherwise the user is rejected.
BTW, if you don't want to implement authentication yourself, you can use Auth0, check out VanillaJS SPA and PHP quickstart
I hope this information helps. Cheers!
Authenticating REST API's with JavaScript front-ends is difficult because the JavaScript code is completely readable by anyone visiting the site so storing any kind of login credentials is no good.
With a standard Server to Server set-up simply using basic auth over HTTPS is more than enough but basic auth is no good for JavaScript SPA's as the credentials are in plain view.
For SPA's you need to be looking at JSON WebTokens, as your back end is in PHP you need to be looking at PHP-JWT from firebase. You can get the code here: https://github.com/firebase/php-jwt or recommended using composer:
composer require firebase/php-jwt
The package makes implementing JWT super simple see the docs for a complete code example. Also check out the JWT for a complete break down https://jwt.io/
I suppose Jwt (https://jwt.io/) is good solution for your question.
On the client side you can store the token on the localStorage or some global variable (for SPA).
You can transfer token on the HTTP header or as request parameter. It works.
Also you can see https://auth0.com/blog/angularjs-authentication-with-cookies-vs-token/

Proper OAuth2 flow for public first-party clients

I'm a regular reader here at stack overflow but this is my first question.
I'm developing an authorization-server using the OAuth2 specs. And I just got stuck with how do I ensure the first-party client authenticity while using the password flow. I read many forums and this is what I got:
Javascript single-page clients
This blog post by Alex Bilbie, he states that to avoid the client_secret problem we should just:
It’s simple; proxy all of your API calls via a thin server side component. This component (let’s just call it a proxy from here on)
will authenticate ajax requests from the user’s session. The access
and refresh tokens can be stored in an encrypted form in a cookie
which only the proxy can decrypt. The application client credentials
will also be hardcoded into the proxy so they’re not publicly
accessible either.
But now this proxy can be accessed by someone impersonating my
angular app. And then I came across this blog post from Andy
Fielder: How Secure is the OAuth2 Resourc Owner Password Flow
for Single Page Apps. He basically says to rely on CORS to
avoid impersonating JS clients.
It is a good idea to use both approaches to secure my JS app?
Native Apps (Desktop and Mobile)
In the case of mobile apps, I only found cases for Authorization
Code and Implicit flows. This is not what I want, as the redirects
will compromise the user experience. So my thoughts on this is:
I will use the ROP flow and then register the client with a
client_id generated for this particular installation and attach it
to the user account, receiving the access_token and a
client_secret as response. Any other token request made by this
client MUST carry this credentials (as the client_id is specific
for the installation, I will be able to check if this client is
already authenticated). This way if someone uses any credential for
impersonating a client, or even registers a bogus client, I can take
mesures to revoke the user and client access.
I know that this can be overthinking, and I also know that some of this matters doesn't avoid anything. I just feel that is my job to protect my API as much as I can.
I would really appreciate your thoughts about this matters! Am I really overthinking? Should I just use the concept of a 'public client' and carry on?
Thank you all and happy coding!
First of all, this problem is not a common priority because most applications are developed first with website, and after with the API. This is probably the reason because no one knows how to deal first clients with oauth2, because everyone have developed other ways to do that and oauth2 is needed only to grant user access to third party applications.
Even if you have develop the oauth2 authorization server only for your first clients applications (thinking about a single authentication mechanism instead of developing many), you should try to develop the authorization code or implicit grant types. You will realize that you need a way to check what user is actually logged in.
The two common methods are:
user session (based on Cookies)
user access from localStorage (based javascript)
In either ways you need to check your application security, user session is vulnerable to CSRF, localStorage are vulnerable to XSS. There are a lot of articles about how to secure your website against either, so I will not suggest anything here, you just need to know that they exist.
Now that you choose your authentication method we can start to do some consideration about:
Javascript single pages applications
Proxy
Having a proxy that filter all requests in my opinion is like to have a door with the keys always inserted. It's useless even build the door.
However, for session based authentication it's the only way to do it. Allowing session authentication on your Rest API will open to CSRF security issues, so you need to have a proxy layer that get the user session, retrieve the access token from the session and do the request to the Rest API adding the Authorization header.
CORS
With this method you need to store the user access token in the localStorage, because the token is retrieved from the Js client directly.
Using CORS you are sure that other websites cannot do requests to your Rest API from a browser. But your first client need to be public (ie: it does not have a client_secret).
Native Apps (Desktop and Mobile)
In my first application I tried to use the same mechanism that you suggest to secure the auth flow. However that type of mechanism require that you identify every user client in an unique way. This is not possible in iOS for privacy reasons and with some probability it will denied in the future releases of Android. So you should rely on a public client and add only the client_id in your native application code.
This means that your native app client/your js client can be impersonalized? Yes, and there is no way to prevent this with oAuth2 resource owner password credentials grant type.
The main reason about this is because oAuth2 is not for authentication, only for third-party authorization, and that grant type was added only for specific third-party applications trusted enought to use directly the user password. You could read more about this argument here and here.
At the end
You still need a way to auhorize your user, and I think that the best you can achieve using oAuth2 is what Auth0 did.
Essentially this Saas manage your users with an oAuth2 server + OpenID connect, so you are always managing your users like its a third-party application and everything works fine.
Indeed, you can see on this page that for mobile applications they suggest to use a browser based login form, because the native one can be impersonalized by everyone that decompile your application, but if you wrap it into an authorization code flow it works fine.

Categories