How to integrate azure b2c with react - javascript

I am working with react and I have to give my user login through Azure B2C, So I am trying to do that but I am not able to find out how to do that and what is the.
What I have tried
I got this example from Microsoft site which is done using plain JavaScript (vanilla), I have no idea how I will implement this in my react code.
So I tried to move with some react library, I google around and found This library
I have followed the same code they have written, but when I hit login button it takes me to login page of azure, So in my app.js I am doing console.log(authentication.getAccessToken()); after login it throws null, I don't know why
My code
authentication.initialize({
// optional, will default to this
instance: 'https://login.microsoftonline.com/tfp',
// My B2C tenant
tenant: 'mytenant.onmicrosoft.com',
// the policy to use to sign in, can also be a sign up or sign in policy
signInPolicy: 'B2c_signupsignin',
// the the B2C application you want to authenticate with (that's just a random GUID - get yours from the portal)
clientId: 'fdfsds5-5222-ss522-a659-ada22',
// where MSAL will store state - localStorage or sessionStorage
cacheLocation: 'sessionStorage',
// the scopes you want included in the access token
scopes: ['https://mytenant.onmicrosoft.com/api/test.read'],
// optional, the redirect URI - if not specified MSAL will pick up the location from window.href
redirectUri: 'http://localhost:3000',
});
And then on click of login I am doing this
const Log_in = () => {
authentication.run(() => {});
};
in my app.js I am doing like below
import authentication from 'react-azure-b2c';
function App() {
console.log(authentication.getAccessToken());
}
So initially it is showing null which is fine, but after login also it is throwing error only.
So I was not able to resolve this, that's why I move to the other library which is almost similar to this
This one
So here when I click on login button I am getting error as
The example I got from Microsoft with valina Javascript, I think that is the perfect way to do but How can I imliment that through react I don't know
This the code with vanilla js
I have been stuch here from long time i don't know what to do now, not able to find good example on google to implement it with react
PS: I am using react hooks functional component to write my code, please guide me through this
I just want to implement this using react in a proper way, I know out tehre so many peoples who are already using this, so I just want to see a good example.
Edit / update
I tried doing like this
b2cauth.initialize({
instance: 'https://mylogin.b2clogin.com/tfp',
tenant: 'mylogin.b2clogin.com',
signInPolicy: 'B2C_1_SigninSignupUsername',
clientId: 'fc3081ec-504a-4be3-a659-951a9408e248',
cacheLocation: 'sessionStorage',
scopes: ['https://mylogin.b2clogin.com/api/demo.read'],
redirectUri: 'http://localhost:3000',
});
b2cauth.run(() => {
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
});
I check Microsoft link pasted as answer, and changed instance:
instance: 'https://mylogin.b2clogin.com/tfp',
to
instance:'https://my-tanent-name.b2clogin.com/tenent-id/oauth2/authresp',
but I am getting error as bad request
and I check network tab and I check the url it is hitting and it is hitting below
https://login.microsoftonline.com/common/discovery/instance?api-version=1.0&authorization_endpoint=https://my-tenatnt-name.b2clogin.com/tenant-id/oauth2/authrespmy-tenant-name.b2clogin.com/b2c_1_signinsignupusername/oauth2/v2.0/authorize
I tried removing https from instance and hit it like this
//mytenant.b2clogin.com/tenant-id/oauth2/authresp
it throws error as Uncaught AuthorityUriInsecure
I think it is going to wrong place

Your coordinates for the b2c instance are not correct (see note). You can find more details: https://learn.microsoft.com/en-us/azure/active-directory-b2c/b2clogin
If you like you can use this sample, which shows how to use B2C policy from React application using oidc-client.js library. By default it is configured to use PKCE but you can configure it to use implicit flow instead if needed (not recommended).
Complete instructions provided in the git repo but here is the high level overview.
You need to first create application in b2c along with the policy (not shown). You should add two redirect uris -- https://localhost:3000 and https://localhost:3000/callback.html
You can also add permissions in case you like to receive an access_token in addition to the id_token.
Your manifest should look similar to:
{
"id": "443ca8db-7bd1-4ebd-9671-ce94e006a18a",
"acceptMappedClaims": null,
"accessTokenAcceptedVersion": 2,
"addIns": [],
"allowPublicClient": null,
"appId": "50d2c416-a5ad-4c5c-b36a-0d1ac5b48167",
"appRoles": [],
"oauth2AllowUrlPathMatching": false,
"createdDateTime": "2020-09-02T00:11:35Z",
"groupMembershipClaims": null,
"identifierUris": [],
"informationalUrls": {
"termsOfService": null,
"support": null,
"privacy": null,
"marketing": null
},
"keyCredentials": [],
"knownClientApplications": [],
"logoUrl": null,
"logoutUrl": null,
"name": "OIDC-Test-APP",
"oauth2AllowIdTokenImplicitFlow": false,
"oauth2AllowImplicitFlow": false,
"oauth2Permissions": [],
"oauth2RequirePostResponse": false,
"optionalClaims": null,
"orgRestrictions": [],
"parentalControlSettings": {
"countriesBlockedForMinors": [],
"legalAgeGroupRule": "Allow"
},
"passwordCredentials": [],
"preAuthorizedApplications": [],
"publisherDomain": "contoso.onmicrosoft.com",
"replyUrlsWithType": [
{
"url": "http://localhost:3000/signin-callback.html",
"type": "Spa"
},
{
"url": "http://localhost:3000/",
"type": "Spa"
}
],
"requiredResourceAccess": [
{
"resourceAppId": "00000003-0000-0000-c000-000000000000",
"resourceAccess": [
{
"id": "37f7f235-527c-4136-accd-4a02d197296e",
"type": "Scope"
},
{
"id": "7427e0e9-2fba-42fe-b0c0-848c9e6a8182",
"type": "Scope"
}
]
},
{
"resourceAppId": "18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85",
"resourceAccess": [
{
"id": "d5515006-5646-4398-ad59-fffc357f3423",
"type": "Scope"
}
]
}
],
"samlMetadataUrl": null,
"signInUrl": null,
"signInAudience": "AzureADandPersonalMicrosoftAccount",
"tags": [],
"tokenEncryptionKeyId": null
}
Clone the repo and update the settings present inside AuthSettings.ts to match your tenant. You must update client_id and contoso which is the tenant name.
const settings = {
// This is the metadata endpoint
authority: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_signup_signin',
// Turn off calls to user info since CORS will block it
loadUserInfo: false,
// The URL where the Web UI receives the login result
redirect_uri: 'http://localhost:3000/signin-callback.html',
// The no longer recommended implicit flow must be used if CORS is disabled
// If you want to use impicit flow use id_token instead of code for the return type.
response_type: 'code',
// Other OAuth settings
client_id: '18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85',
// openid is required, remove https://contoso.onmicrosoft.com/test/Read if access_token is not required.
scope: 'openid https://contoso.onmicrosoft.com/test/Read',
// Supply these details explicitly. Directly copied from azure ad b2c policy metadata endpoint.
metadata: {
issuer: 'https://contoso.b2clogin.com/9859cd0c-9d99-4683-abcc-87462f67a0bc/v2.0/',
authorization_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1a_signup_signin',
token_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1a_signup_signin',
jwks_uri : 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1a_signup_signin',
end_session_endpoint: "https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?p=b2c_1a_signup_signin&post_logout_redirect_uri=http%3A%2F%2Flocalhost:3000%2F"
},
} as UserManagerSettings;
Build and run the app using yarn or npm
Application will launch by default on http://localhost:3000
Click Login and it should take you to the b2c policy to complete the journey.
After you complete the journey in the b2c policy you will be redirected back to the application.

Related

Meteor loginWithApple oauth - "Service not configured"

I'm adding Apple login, the latest oauth package to join Meteor, but I'm running into the error message "Service not configured". It seems that a lot of the solutions [another] talk about using ServiceConfiguration to fix these errors, but I haven't had to initialize any of the other meteor logins such as loginWithGoogle or loginWithFacebook. Based on my reading through the github package Meteor.loginWithApple is configured the same way as these existing login functions. What configuration issue might be triggering this?
When I look at Meteor.settings.private.oAuth, apple is right there alongside google and facebook.
First, I installed these two https://atmospherejs.com/quave/accounts-apple, https://atmospherejs.com/quave/apple-oauth
meteor add quave:accounts-apple
meteor add quave:apple-oauth
Then set up the config in settings.json alongside facebook and google oauth per this guide.
settings.json:
"apple": {
"teamId": "yyexamplexx",
"clientId": "com.example.client",
"keyId": "zzexamplewq",
"secret": "zxcvsdfasdfexamplezlongstrxcvsdfasdf",
"redirectUri": "https://example.com/apple-redirect"
},
Client:
continueWithApple = () => {
Meteor.loginWithApple({}, function(err, res) {
if (err) {
console.log(err);
}
//running ok
});
};
<Form.Button
id="appleid-signin"
fluid
basic
className="continue apple"
data-color="black"
data-border="true"
data-type="sign in"
onClick={() => {
this.continueWithApple();
}}
>
For some reason the config oauth settings aren't being passed on, so we had to do something like the following in order to set up the credentials and stop the "Service not configured" error message:
Meteor.startup(() => {
// remove any existing service so you can configure the latest one
Accounts.loginServiceConfiguration.remove({ service: "apple" });
// setup apple login, drawing from your settings.json
Accounts.loginServiceConfiguration.insert(Meteor.settings.private.oAuth.apple);
...
)}
Our configuration looked something like:
"private": {
"oAuth": {
"apple": {
"secret": "-----BEGIN PRIVATE KEY-----\nxyzexamplexyz\n-----END PRIVATE KEY-----",
"redirectUri": "https://www.example.com/_oauth/apple",
"clientId": "com.example.client",
"teamId": "WXYZ8EXAMPLE",
"keyId": "456EXAMPLE",
"scope": "name%20email",
"responseMode": "form_post",
"responseType": "code",
"service": "apple"
}
It seems to be important that the redirectUri ends with _oauth/apple since meteor's loginWithApple is looking for that. Didn't need to handle the callback at all, the packages below take care of it.
meteor add quave:accounts-apple
meteor add quave:apple-oauth
Also important to put the %20 in the scope name%20email...it just worked.

Do not see onQuery callback triggered in NodeJS actions-on-google

Overview
I am using the Node.js library actions-on-google client to build a smarthome action for the Garage Door device type. This action is deployed as a Cloud Function in GCP. I can confirm that the following works perfectly so far:
Accounting linking with our OAuth flow
Responding to sync intents (ie. onSync() in the client)
Responding to execute intents (ie. onExecute() in the client)
Problem
Despite that other callbacks (onSync() and onExecute()) work fine, we do not see any evidence of onQuery() being called no matter what. There aren't any errors showing in Stackdriver nor are their any logs being generated in Stackdriver under the "Google Actions" filter either.
We expect onQuery() to run when we ask Google Assistant things like is the garage door open? and is Matt's Door closed?
We tried removing async to see if the call was hanging
We tried removing headers in the lambda
We tried removing all other code and redploying to isolate onQuery()
Code
The following code shows the simple onQuery() callback. onExecute() and onSync code has been removed for clarity.
'use strict';
const functions = require('firebase-functions');
const {smarthome} = require('actions-on-google');
const app = smarthome({
jwt: require('./XXXXXXXXX-XXXXXXXXXX.json'),
debug: true,
});
//
// Note: Removed onSync() and onExecute() for clarity
//
app.onQuery(async (body, headers) => {
// Expecting to see these logging statements in
// Stackdriver like we do for onExecute() and
// onSync() ... but nothing ever shows up.
console.info('=== onQuery.body', body);
console.info('=== onQuery.headers', headers);
// We have hardcoded the following ID and a "closed"
// state. It matches a valid device ID to the testing
// account we are using.
return {
requestId: body.requestId,
payload: {
devices: {
'2489e4a92799728292b8d5a8b1c9d177': {
on: true,
online: true,
openPercent: 0,
}
}
}
};
});
exports.smarthome = functions.https.onRequest(app);
We considered the possibility that the JSON returned in the call to onSync() might be missing a trait or something that prevents it from responding to a query intent properly but we have not been able to identify anything that might be incorrect or missing. Here is the JSON payload returned from onSync():
{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"payload": {
"agentUserId": "1836.15267389",
"devices": [{
"id": "1234",
"type": "action.devices.types.GARAGE",
"traits": [
"action.devices.traits.OpenClose"
],
"name": {
"defaultNames": ["Smart Garage Door"],
"name": "Matt's Door",
"nicknames": ["Matt's Door"]
},
"willReportState": true,
"attributes": {
"openDirection": [
"UP",
"DOWN"
]
},
"deviceInfo": {
"manufacturer": "ABC Corp",
"model": "test",
"hwVersion": "1.0",
"swVersion": "1.0"
}
}]
}
}
Expected Result
We expect Google Assistant to respond with "Garage door is closed" or some other equivalent. Instead, we receive "Sorry, I can't reach Matt's Door right now. Please try again."
Answering my own question here in case anyone else has this trouble. The reason why my action was handling the SYNC and EXECUTE intents but not the QUERY intent came down to what default/user names I assigned each device in the SYNC response.
Ultimately, I started using the following and my action began responding to QUERY intents as expected again:
...
name: {
defaultNames: ['Garage Door'],
name: door.name,
nicknames: [door.name, 'Garage Door']
},
...
where door.name is a name which is set by the user and is returned by an API call.

Microsoft Graph API token validation failure

I would use Microsoft Graph API in my Angular Web application.
First I make connexion using msal library
When I try log in with my profil I get this error
I have configured my app as the mentionned in the official git sample
MsalModule.forRoot({
clientID: "Tenant ID",
authority: "https://login.microsoftonline.com/common/",
redirectUri: "http://localhost:4200/",
validateAuthority : true,
popUp: true
}),
Authetification is working and I get the token.
Then when I'm in home page I make a second request to Microsoft Graph API to get user information using that token.
getProfile() {
let header= new Headers();
let tokenid= sessionStorage.getItem('msal.idtoken');
header.set('Authorization', 'Bearer ' + tokenid)
let url ="https://graph.microsoft.com/v1.0/me/"
return this.http.get(url,{headers:header});
}
}
I get an 401 Unauthorized error with a response :
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "xxxxxx",
"date": "2018-10-09T22:58:41"
}
}
}
I don't know why MG API is not accepting my token, Am I using wrong authority url ?
UPDATE: I have understood that actually I get id_token which is different from access token. How can I get Access token from MSAL library to make MS GRAPH API calls ?:
According to the same sample you can also attach an HttpInterceptor that will automatically attach the access token to each (external) HTTP call.
By reading through the documentation I found the following information.
consentScopes: Allows the client to express the desired scopes that should be consented. Scopes can be from multiple resources/endpoints. Passing scope here will only consent it and no access token will be acquired till the time client actually calls the API. This is optional if you are using MSAL for only login (Authentication).
That suggests that using the HttpInterceptor doesn't only attach the access token, but also retrieves it. The token that you're seeing is probably just a token for your application, but isn't a valid token for the Graph API.
Internally it uses getCachedTokenInternal(scopes: Array<string>, user: User) to get a new access token for specific scopes code found here. I'm not sure if you can use this method as well to get a new token for that resource. I would just use the interceptor.
You could try to copy the access token and see how it looks like on jwt.ms (a Microsoft provided JWT token viewer) or jwt.io.
Any tokens valid for Graph should have the Audience of https://graph.microsoft.com, so if you inspect the token (in jwt.ms) it should at least have this value.
"aud": "https://graph.microsoft.com",
The issue is that you're using the id_token instead of the access token:
let tokenid= sessionStorage.getItem('msal.idtoken');
becomes something like:
let tokenid= sessionStorage.getItem('msal.token'); // or msal.accesstoken
Update(per Phillipe's comment)
You need to select the scopes that you want to target in your application. So, it looks like you want the user profile, so you'll want to add the consentScopes property to specify which scopes your app will use:
MsalModule.forRoot({
clientID: "Tenant ID",
authority: "https://login.microsoftonline.com/common/",
redirectUri: "http://localhost:4200/",
validateAuthority : true,
popUp: true,
consentScopes: ["user.read"]
}),
Make sure you add your endpoint to Resource Map configuration. See this link: https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp
export const protectedResourceMap:[string, string[]][]=[ ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];

Node.js Loopback Framework + Twitter oauth doesn't work on a live server

I'm using Loopback Third Party Login Passport with Node-Twitter library for api calls.
I've created
var client = new Twitter({
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
which is neccessary for node-twitter to work and I specified all those credentials manually for my twitter account because i'm not able to obtain token and tokenSecret from my accountIdentity model.
I've got an 'add twitter account' button which redirects user to Twitter Authorize page and implements oauth and then redirects user back to the page (on a local machine) but on a live server it redirects to /auth/twitter and then nothing.
I make twitter api calls like friends/ids, users/lookup, account/verify_credentials and they work OK on my local machine. I expected them to work on a live server too, but they don't.
at apps.twitter.com my callback URL is set to http://dev.mysite.com/auth/twitter/callback
providers.json
{
"twitter-login": {
"provider": "twitter",
"authScheme": "oauth",
"module": "passport-twitter",
"callbackURL": "dev.mysite.com/auth/twitter/callback",
"authPath": "dev.mysite.com/auth/twitter",
"callbackPath": "dev.mysite.com/auth/twitter/callback",
"successRedirect": "dev.mysite.com",
"failureRedirect": "dev.mysite.com/login",
"consumerKey": "my key is specified here",
"consumerSecret": "my key is specified here",
"failureFlash": true
}
}
(i tried leaving it "as is" which means removing dev.mysite.com, and i also tried adding http:// before url)
npm packages are all up-to-date on a server
my question is how to make it work at least for 1 (my) account for now
after ~3days solved the problem: i should have paid attention to the details
Loopback adds "/api/" in the global config to all API calls. Otherwise, it treats path as a route.
providers.json :
{
"twitter-login": {
"provider": "twitter",
"authScheme": "oauth",
"module": "passport-twitter",
"callbackURL": "/api/auth/twitter/callback",
"authPath": "/api/auth/twitter",
"callbackPath": "/api/auth/twitter/callback",
"successRedirect": "/",
"failureRedirect": "/login",
"consumerKey": "key",
"consumerSecret": "key",
"failureFlash": true
}
}
while on the client side I had to add "/api/" to each API call url for example
function fetchFollowers() {
const URL = "/api/fetchfollowers";
return fetch(URL, {method: "GET"
})
.then(response=> Promise.all([response, response.json()]));
}
and
Add Twitter Account
instead of
Add Twitter Account

Google Developer OAuth Consent: The supplied API key is not configured for use from this referrer

I'm trying to play around a little bit with the Google Calendar API but I can't create a OAuth ID ( as mentioned in this example: Google Calendar JS API.
I created a project, clicked Cerdentials and if you try to create an OAutho-client-Id you will be forwarded to the configure consent tab.
Here you have to enter your email address (is standard google account) and a project name. Then pressing save leads to an error:
{
"error": {
"code": 403,
"message": "The supplied API key is not configured for use from this referrer.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developer console API key",
"url": "https://console.developers.google.com/project/648364020234/apiui/credential"
}
]
}
]
}
}
The URL metioned in this JSON I can't access (no rights).
What can I do to get a simple oAuth ID?
Tried with several new projects, other naming of the consent projet name.
Also tried to create an API key which can be referred by all clients (empty field).
Any ideas anybody?

Categories

Resources