Firebase Auth + Own Api - rest

is it possible to use only the firebase auth and then create an own api with own database?
So I write an REST API which uses the firebase token to authentificate.
Thanks!

It depends on the technology that you will be using for the backend API. There is a Firebase Admin SDK, that is aimed at Java, Python and Node developers, but I think the functionality that you are looking for is only available in the Node SDK (although I believe that there are workarounds for this).
The way this works is that after your user signs in on the client side, they can request a token using firebase.auth().currentUser.getIdToken() which can then be passed to your backend which can then be verified, see the below example for how it could be done using Node and Restify.
const server = restify.createServer({});
server.use(validateJwt);
function validateJwt(req, res, next) {
if(!req.headers.token){
//reject
}
admin.auth().verifyIdToken(req.headers.token).then(decodedToken=>{
console.log(`token for user ${decodedToken.sub} valid`);
admin.auth().getUser(decodedToken.sub).then(user=>{
console.log(`fetched user ${user.email}`);
next();
}).catch(err=>{
res.send(500, 'the user with the ID does not exist in firebase');
})
}).catch(err=>{
console.log(`token validation failed: ${err}`);
res.send(401, 'authentication failed')});
}

I believe you should be able to do this, by using Firebase to authorise the user and then allow read access to a link securely stored for authenticated users only. This could then link to the database, if this is what you mean. I'd assume you may have already started here, but this is where to start Understand Firebase Realtime Database Rules

Related

403 Forbidden while accessing Leycloak rest API with a valid user credentials

I have set up a Keycloak server and a user named 'sample' is given permissions to access the rest ADMIN APIs, I granted permissions to the relevant realm and client_id. And I'm able to access the rest APIs using the postman service using this user credentials 'sample/sample'.
so through Angular application, I was trying to access the API that fetches the roles in a specific realm. since not all the login user will have the rest admin access, I'm using the user credentials(sample/sample) that have the access to admin API, but when I try to access the API, the APIs are forbidden,
this.getKeycloakAccessToken().subscribe((Tokres:any)=>{
console.log('accessToken: ', Tokres.body.access_token);
if(Tokres && Tokres.status === 200 && Tokres.body.access_token){
this.getKeycloakRoles(Tokres.body.access_token).subscribe((roleRes:any)=>{
console.log(roleRes);
},(roleErr:any)=>{
console.log('error while fetching roles..');
console.log(roleErr);
})
}
},(tokErr:any)=>{
console.log('error while accessing keycloak token...');
console.log(tokErr);
})
getKeycloakAccessToken(){
const url = 'http://keycloak-keycloak.router.default.svc.cluster.local.......nip.io/auth/realms/myRealm/protocol/openid-connect/token';
const authH = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const body = new HttpParams()
.set('username', 'sample')
.set('password', 'sample')
.set('grant_type', 'password').set('client_id','rest-client');
return this.http.post(url, body,{headers:authH,observe:'response'});
}
getKeycloakRoles(access_token){
const url = 'http://keycloak-keycloak.router.default.svc.cluster.local........nip.io/auth/admin/realms/myRealm/roles'
const authH = new HttpHeaders().set('Authorization','Bearer ' + access_token);// ({'Authorization':'Bearer ' + access_token});
return this.http.get(url,{headers:authH,observe:'response'});
}
and when I tried to debug, the access_token shown in console is different from that of request headers
[![network log][2]][2]
After debugging for couple of days, I figured out the reason for the difference in Access token, the API call is being invoked with the access_token of logged in session, though the program has source code written to set the headers set with access token of user 'sample/sample'. is there any way to trigger the API with the given access_token rather with the logged in user's access_token.
This might not be the solution, but just a couple of workarounds that worked for me.
Allow permissions (set 'Relam Management') to all the logged in users from the key cloak admin console, this way irrespective of user, whoever logs in will be able access the rest Admin APIs, follow this below
reference
From keycloak client library, we have a initializeKeycloak() , that has configurations set for the application, so disable the 'enableBearerInterceptor' which will say the application not to use the access_token generated by logged in user to set the headers of each request. this way we can avoid the forbidden error.
But with approach no.2, you can not use the AT of logged in user as we r disabling the enableBearerInterceptor.
And with solution no.1, if you are not having control on who are the users logging in to your application, i,e using some third party tool like LDAP to set the users, then it this won't serve the solution.

Posting a tweet as a logged in user in Flutter

So my problem is that I need to make a tweet (update) using a users authorised session which I retrieved in Flutter using the flutter_twitter_login package. I also have integrated Firebase Authentication and have access to a UserCredential. I also use the dart_twitter_api library for sending Twitter requests. I am new to the Twitter API and Flutter so I would appreciate the help.
I found the solution given my setup and here I will post the details for anyone else in need.
Firebase authentication is not required to solve this problem but you do need the flutter_twitter_login and dart_twitter_api packages. You can find alternative packages for the latter as well, but not the former as of this time.
You need to pass the Twitter session's token and secret you retrieve after a successful login as the initialisation parameters of the dart twitter API for the values access token and secret respectively.
final twitterApi = TwitterApi(
client: TwitterClient(
consumerKey: apiKey,
consumerSecret: apiSecret,
token: session.token,
secret: session.secret,
),);
From the code above just store the all 4 keys in String variables elsewhere in your Dart library and replace the above references with your variables.

Is there a way to get a users Bitmoji using Access tokens from Snapkit login web api?

I am attempting to use the snapkit login web api for a hybrid application. I have successfully been able to intercept the access token in the redirectURL. I was wondering if there was a way to get the users Bitmoji using this access_token and either the functions found in login.js or an http get call?
Api docs: https://docs.snapchat.com/docs/login-kit/#web
currently I have the access_token in a deeplinking function on my app.component.ts . I have attempted to push to a new page with the navController and passing in the access_token as a parameter, but this doesn't help when attempting to get the users information.
Thanks in advance for your help.
Here is the Deeplinking where I intercept the access_token using myapp://settings-set/ as the URL redirect and attempt to push a new page with the matching url.
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
this.deeplinks.routeWithNavController(this.nav,{
'/settings-set/:token': SettingsSetPage
}).subscribe((match) => {
// match.$route - the route we matched, which is the matched entry from the arguments to route()
// match.$args - the args passed in the link
// match.$link - the full link data
this.nav.push(SettingsSetPage, {
args: match
});
console.log('Successfully matched route', match.$args);
},
(nomatch) => {
// nomatch.$link - the full link data
console.error('Got a deeplink that didn\'t match', nomatch);
});
});
}
In the setting-set page I recieve the parameter using:
this.args = navParams.get('args');
console.log("this is args", JSON.stringify(this.args));
but don't know how to use the information to get the users information
The Bitmoji API can be very confusing at times. I suggest using Passport, a Node JS tool for OAuth, along with the Ionic framework. Snapchat has a guide that explains how to grab specific fields, such as user name and Bitmoji avatar, from a user's Snapchat profile using passport. You can follow this tutorial to learn how to integrate Node JS into your existing ionic app.
So in conclusion, try following these steps:
Integrate Node JS into your existing ionic app
Install Passport and follow Snapchat's guide for obtaining specific fields from the user's profile
Yes, like Mora said you can use passport which will make your life easier. We also have a sample passport app running here:
From the context you provided it seems like you have generated the code and not the access_token. After you get the code from the redirect url, you need to use the code to generate the access token. Check section 2.5 here.
Once you have the access token you can use that to request information. The crux of this lies in setting the "scope" correctly. To get the Bitmoji avatar make sure you set your scope to this at the very least:
var scope = ['https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar'];
Hope this helps!

How to impersonate an admin user when using getClient() in the Google API NodeJS client

Per the recommendation in the defaultauth sample, I am trying to access the directory api for a domain which I have created a service account for. Here is the code I am attempting to connect with:
import { google } from 'googleapis'
const authClient = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/admin.directory.user.readonly']
})
const service = google.admin('directory_v1')
console.log(
await service.users.list({
auth: authClient,
domain: <redacted>
})
)
However, when I attempt to connect I recieve an error saying Error: Not Authorized to access this resource/api. If I remove the creds.json file in ~/.google, the error changes to saying that it cannot find the credentials file. Also, I am able to access a bucket using the same file, so I'm pretty sure my local environment is set up correctly, authentication wise. I have also worked for the past few days with someone on the support team G Suite API team, who assures me that things are set up correctly on my domain.
After looking around online, it seems the thing I am missing is impersonating an admin account when trying to connect with my service-account. I have found a few examples online of doing this with a JWT auth strategy, but I would like to continue to use the default auth client, in order to abstract away the implementation details. Is this possible? If so, what do I have to change? I have tried setting subject, and delegationEmail in both of the calls (getClient and list).
Any help would be greatly appreciated.
Just set subject of the client object:
authClient.subject = 'your email address'
Google's api documentations highly varies by language. No standart. Something documented in PHP client may be missing in nodejs client and it can take hours to find out how to do it.
You can pass clientOptions.subject in the constructor.
import { google } = from 'googleapis';
const authClient = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/admin.directory.user.readonly'],
clientOptions: {
subject: "your email address"
});

Read logged in User details from SSO server in Blue mix

I am working on Node.js application with Cloudant database. I was able to do IBM IDP authentication with SSO server on Blue mix via the SSO service.
My issue occurs after successful authentication, I am unable to get JSON object that can give me all the user attributes that I need, for example, is the logged in person a manager? if yes then his serial number, name etc
Does anyone know how to retrieve the information from IBM SSO service?
Kindly let me know as soon as possible.
You can check the request.user object returned after successful authentication. It returns some information about the logged in user, but each provider returns different data.
For example, for LinkedIn logged users it returns displayName, firstName, lastName and emailAddress.
The snippet code below prints the request.user JSON object in the application log, so you can see what is available and retrieve as needed.
app.get('/auth/sso/callback', function(req, res, next) {
var redirect_url = req.session.originalUrl;
passport.authenticate('openidconnect', {
successRedirect: '/hello',
failureRedirect: '/failure',
})(req,res,next);
});
app.get('/hello', ensureAuthenticated, function(request, response) {
response.send('Hello, '+ request.user['id'] + '!\n' + 'Log Out');
console.log(JSON.stringify(request.user));
});
After user logs in you can run:
cf logs <app-name> --recent
to see results from console.log code.