Do you need firebase admin sdk when creating admin web? - reactjs

I'm currently working on a small project using firebase. My team member is working on IOS and android while I'm trying to build a custom admin page using React.
In the app, users can signup with their phone and send a request for permission by attaching few documents.
I have to build an admin page to approve or deny these documents. For that I need to get list of all user from User Collection and view all the documents that was submitted and be able update user field 'isApproved' to true or false.
I was thinking of simply creating a new admin account directly in firebase and use that account to signin to admin page and perform the following actions (manipulate normal user info field). But I found out about firebase admin SDK. Do I need to use this in my case?
I may need to send push notifications to all users signed up and create user, update user, delete user account later on.
Give the situation should I use firebase admin SDK?
Can someone give me advice on how to set up the overall structure?

First things first, you should not use the Admin SDK on frontend. The Admin SDK has privileged access to all Firebase resources and does not follow any security rules either. You should always use Admin SDK in a secure environment like Firebase Cloud Functions or your own server.
I am not entirely sure what actions you need to perform while accepting/rejecting the documents. If you need to read/write a specific part of a database (which only a admin can access) then you can use Firebase security rules. You would have to add a Custom Claim to the admin user or store their UID in a database.
But if you need to do multiple things (maybe sending an email to user, doing some actions using 3rd party API), I'll recommend using a Cloud Functions with the Admin SDK.
How will that work?
You will have to create a Cloud Functions to accept/reject the documents.
When the admin accepts/rejects a document, you can pass details of that user (userID, document info and if the docs were accepted to the
cloud function) to the cloud function and process it over there.
The callable function may look like:
exports.verifyDocs = functions.https.onCall((data, context) => {
const {uid, token} = context.auth
if (!uid) return "Unauthorized"
if (!token.admin) return "Forbidden"
//The user is an admin
//Do database updates
//Any third party APIs
});
If you use callable functions, Firebase will automatically add auth info of the user calling that function. In the example above, I've assumed the user will have an admin custom claim but if you want to keep things simple based on UIDs you can do so by:
const adminUIDs = ["uid1", "uid2"]
if (!adminUIDs.includes(context.auth.uid)) return "Forbidden"
To call the function from your React app:
const verifyDocs = firebase.functions().httpsCallable('verifyDocs');
verifyDocs({ userID: "userID", text: messageText })
.then((result) => {
// Read result of the Cloud Function.
});
Any thing you pass in the function above will be available in your cloud functions in the 'data' parameter.

Related

MSAL React not showing roles, but they are in the token

I'm trying to implement App Roles in a single-tenant React + .NET Core app of ours. This app has successfully been authenticating users via MSAL, so this is just an incremental addition.
I have the app roles set up in Azure AD, and I have the Authorize attribute with role restrictions working in the .NET back-end, but for some reason I'm unable to get the roles via the react MSAL library, even though when I manually decode the token I see them in there.
I was referring to this MS sample for my code. In my index.js, I have the following:
export const msalInstance = new PublicClientApplication(msalConfig);
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}
Then, in the test page I have, I'm trying to access the roles array in this way (just as a test to print them out):
const TestComponent = () => {
const { instance } = useMsal();
useEffect(() => {
const activeAccount = instance.getActiveAccount();
setTokenRoles(activeAccount?.idTokenClaims?.roles);
// I've also tried:
// setTokenRoles(activeAccount?.idTokenClaims['roles']);
}, [instance]);
return (
<div>
ROLES: {JSON.stringify(tokenRoles)}
</div>
);
};
Unfortunately, tokenRoles is null. When I inspect entire idTokenClaims object, I see all the other claims, but no roles. However, I do see them in the token itself:
{
...
"roles": [
"Packages.Manage"
],
...
}
I'm really hoping to avoid manually decoding the token. There has to be a way to get it out of MSAL.
Jason Nutter's comments provided the answer, and in case this helps others I figured I'd give it a write-up.
Per the MS docs, I put the app roles on the back-end app registration. This is why I am able to have the Authorize(Roles = "Role") attribute work on the back-end. The reason I can see the roles in the access token is that the token is retrieved with the scope for that back-end API. But because I don't have those roles mirrored on the front-end app registration, I don't see anything in the id token.
There would be two options if you wanted to use the Azure app roles:
Mirror the app roles in the front-end app registration. In this way you'd have access to the roles in the id token. This sounds not good because I could foresee a typo or mismatch causing weird issues. I'm sure there might be a way using the Azure API to have a process that would sync the roles, but that's not worth it in my opinion.
Manually decode the access token on the front-end. The cleanest way I could think of to do this would be to create a roles context that would pull an access token, decode it, and store the roles for child components to refer to.
Another alternative would be to manage roles in the app itself. For us, the application in question is single-tenant, so there's not much need to do that. However, we do have a multitenant app we are moving to MSAL, and in that case we will already need to do things like validate that the tenant is authorized, and we will need more granular permissions than what this internal app needs, so we will likely have role system and have the front-end retrieve role and profile data from the back-end upon authentication through MSAL.
EDIT: What I ultimately did...
I did indeed keep the roles in the back-end only, then created a user context object that the front-end would retrieve. This user context includes the app roles, as well as other convenience data points like nickname, and is used by a React context and provider that I wrap my app in.

IdentityServer4: How to set a role for Google user?

I have 3 applications:
An IdentityServer4 API which provides Google authentication and also provides an access token to authorize the resource API.
A simple Resource API which provides some data from DB.
A simple Client in React which have 4 buttons:
Login, for Google auth
Logout
Get data - a simple request with the access token to the Resource API and gets the data from Db
Get user data - returns user profile and token (for debug purpose)
I didn't put any sample code because my problem is not code related, it's knowledge that I'm missing and I ask for guidance.
The workflow is working just fine: the user press the Login button, it is redirected to IdentityServer4 API for Google Auth. From there it is redirected to a Callback Page from the Client and from there to the Index page. I receive the user data and the token, I can request data from the Resource API and it's working.
My problem is: How do I give a Role to the Google Users ?
I don't have users saved in DB. I want three types of Users: SuperAdmin, Admin, Viewer and each of these roles have limited Endpoints which can access.
For limiting their access I saw that I can use Claims-based authorization or Role-based authorization.
So, my question is how ca I give a Google User who wants to login in my app, a specific Claim/Role ? What is the workflow ? I must save it first in DB ? Or there exists a service from Google where I can add an email address and select a Role for that address ?
Thank you very much !
After you get the response from Google in your callback you can handle the user and do what ever you want to do with it. Below are the some typical tasks that you can do in callback that I took from documentation page of identityserver4 link:
Handling the callback and signing in the user
On the callback page your typical tasks are:
inspect the identity returned by the external provider.
make a decision how you want to deal with that user. This might be
different based on the fact if this is a new user or a returning
user.
new users might need additional steps and UI before they are allowed
in.
probably create a new internal user account that is linked to the
external provider.
store the external claims that you want to keep.
delete the temporary cookie
sign-in the user
What I would do is creating an new internal user account that is linked to the external provider and add a role to that user.
If you don't want to save users in db, you can add an extra claim to user in callback method and use that claim in token. and i think this link will help with that.

Custom React GUI for oidc-client-js

is there a way to user your custom React GUI with oidc-client-js? I know that if you trigger authentication endpoint using:
// PopUps might be blocked by the user, fallback to redirect
try {
await this.userManager.signinRedirect(this.createArguments(state)); //Shows midleware login form
return this.redirect();
} catch (redirectError) {
console.log("Redirect authentication error: ", redirectError);
return this.error(redirectError);
}
Middleware will try to render its predefined login form:
However I have my own React form and I only need to pass to OICDClient params (email,password) and get back User instance to display UserName etc. Something like:
var loggedUser = await this.userManager.signinCustom(state.loginEmail, state.LoginPassword); //Login using credentials
I don't want to write all the logic by myself I really want to use all functionality from OIDCClient - only with my GUI (loginForm, registerForm, updateUserForm etc).
I'm using scaffolded library from MSDN using command:
dotnet new react -o <output_directory_name> -au Individual
Is there any method/implementation to initialise oidc-client-js from React components and not user default GUI forms?
Thanks a lot!
I might be missing some thing but the whole idea of using a 3rd partly federated auth provider be it your own/your company's SSO (say developed using Identity Server 4) or say Google sign in(say using their Firebase JS kit) or Microsoft sign in, Facebook sign in etc. is that you will be redirected to their authentication endpoint where you then use say your google credentials (if you are using google sign in for example) to sign on to google auth servers. Once you do that then a payload (consisting of an identity token and access token) is returned back to your redirect URL which you must configure for your specific app.
By saying you'd like to provide your own sign-in form you are missing the entire point of using a 3rd party authentication provider. Besides, you/your app shouldn't know about user names and passwords and you don't want to have access to all that information. All that you should be interested in knowing whether the user, who are using one of the federated authentication providers, that you would have configured for your app, are who they claim to be and you then delegate all that heavy lifting to your 3rd party authentication provider.
Besides, say your company has a SSO system of their own then all your company's app will use that SSO system and from a UI perspective you want to show the same login screen so as to give a consistent user experience.
In addition, if you show me a google authentication button and then on clicking that button you show me some weird form that doesn't look like the typical google picklist sign-in form then I'll shut down your app before you can say hello, and, I suspect most user would (and should) do the same. The reason being that when you show me a google sign-in page then I know that you/your app will only get back what you need and I wouldn't ever entrust my google user name and password to any other application.
If you really want to have your own authentication form then you'll have to manage user names and passwords yourself, the way we used to do things probably over 10+ years back.
If you decide to go the route of setting up your own authentication system and then say use identity server 4 then yes you can certainly change the UI and customize it to your heart's content, but that will happen at the server level, not at the level of your react app. Point being that in any SSO system the user will be redirected to the that auth provider's endpoint where they then authenticate (and, optionally, provider permission for your app to use certain claims) and once they do that they they are redirected back to your redirect endpoint with a payload (JWT token).
Lastly, even if you could some how wire up a client side sign in form, I'm not sure you would want to use it. Passing passwords & user names over the wire isn't a good idea. You'll always want to use a server rendered sign in form.

Reactjs and Firebase: one login interface for user and admin or separate login interface?

I'm doing a school project using reactjs and Firestore that has 2 users; user and admin. These are the features:
User:
User registers on the website. Upon registration, the system will generate a QR code for the user to be scanned. Upon scanning, the vaccination status of the user will be updated such as the vaccine type, dose, date of vaccination, and etc. The user may also input side effects they've experienced, and view the vaccination graph reports.
Admin:
Admin can log in and scan the qr code, view vaccination graph reports, Vaccine (CRUD), list of the users
Is it okay to have one login interface for both users and admin? Are there any security risk or defining the security rules is already enough?
Or is it preferable to have a separate login interface? If a separate login interface will
be used, would I need Firebase Admin SDK and Cloud Functions (the problem here is that we do not have a credit card for the Cloud functions)?
I am not sure how you are executing the QR Code logic for both admin and users and fetching all these details. Nonetheless, I would like to suggest an approach that you can follow. You can set your authentication based on role and create multiple routes for your application using React Router for Firebase.
For instance, a user should be able to visit a public landing page,
and also use sign up and sign in pages to enter the application as an
authenticated user. If a user is authenticated, it is possible to
visit protected pages like account or admin pages whereas the latter
is only accessible by authenticated users with an admin role.
There is no reason to show a non authenticated user the account or
home page in the first place, because these are the places where a
user accesses sensitive information. In this section, you will
implement a protection for these routes called authorization. The
protection is a broad-grained authorization, which checks for
authenticated users. If none is present, it redirects from a
protected to a public route; else, it will do nothing. The condition
is defined as:
const condition = authUser => authUser != null;
// short version
const condition = authUser => !!authUser;
In contrast, a more fine-grained authorization could be a role-based or permission-based authorization
// role-based authorization
const condition = authUser => authUser.role === 'ADMIN';
// permission-based authorization
const condition = authUser => authUser.permissions.canEditAccount;
The real authorization logic happens in the componentDidMount() lifecycle method. Like the withAuthentication() higher-order component, it uses the Firebase listener to trigger a callback function every time the authenticated user changes. The authenticated user is either an authUser object or null.. If the authorization fails, for instance because the authenticated user is null, the higher-order component redirects to the sign in page. If it doesn't fail, the higher-order component does nothing and renders the passed component (e.g. home page, account page).
You can check this tutorial and get an idea of the approach I was mentioning.
Just a reminder : While Firebase Realtime Database can be used on the free plan, Cloud Firestore is charged by usage. That's why you can set monthly quotas and budget alerts. You can always see the pricing plan, and adjust it, in the bottom left corner of your Firebase project's dashboard.
Also yes Cloud Functions still has a monthly free allowance that's documented in the pricing page. But you will have to provide a credit card and be on a billing plan in order to use it. You will be responsible for paying for any monthly overage. But I don’t think you will need Cloud functions for that matter, just some decent db rules to protect your database and the authentication of your application based on role and routes using React Router for Firebase should be good enough.

Firebase AngularJS full data access

I'm building an app based on Firebase + AngularJS. I'm using User management service by Firebase. I'm able to get all data for Authenticated user, however, I'm not able to retrieve all user data as admin. How can I get full access to Firebase data.
Thanks!
As Frank mentioned in the comment, Firebase doesn't make user account information available to the admin. Rather, some information is available on the client after authentication and it could be sent to be stored as explicit data in Firebase.
The link Frank provide in the comment explains how to do this.
Applications do not automatically store profile or user state. To persist user data you must save it to your database. The callback function will return an object containing the data for the authenticated user, which you can then write to your database.
Here is the core of the example
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});

Resources