React Native, unable to get access token - reactjs

I'm using react-native-app-auth to get access token from azure ad b2c but I'm facing issues in android and in IOS
in android it's showing error that
Unable to complete authorization as there is no interactive call in progress. This can be due to closing the app while the authorization was in process.
https://i.stack.imgur.com/R2Fft.png
and in IOS it's redirecting but not returning anything.
that's my code
const config = {
issuer:
'https://ksg1806.b2clogin.com/tenantId/v2.0/',
clientId: 'clientId',
redirectUrl:
Platform.OS == 'ios'
? 'msauth.com.gfk.consumervoice://auth'
: 'msauth://com.gfkconsumer/Cb7s2L1nogp57%2BKdddohtF8%2Funk%3D',
additionalParameters: {},
scopes: ['openid'],
serviceConfiguration: {
authorizationEndpoint:
'https://ksg1806.b2clogin.com/ksg1806.onmicrosoft.com/b2c_1_signup_signin/oauth2/v2.0/authorize',
tokenEndpoint:
'https://gfkms.b2clogin.com/GFKMS.onmicrosoft.com/b2c_1_signup_signin/oauth2/v2.0/token',
revocationEndpoint:
'https://gfkms.b2clogin.com/GFKMS.onmicrosoft.com/b2c_1_signup_signin/oauth2/v2.0/logout',
},
};
const getAccessToken = async () => {
try {
const authState = await authorize(config);
console.log(authState);
} catch (error: any) {
Alert.alert('Failed to log in', error.message);
}
};
if anyone know about that please help I'm stuck here for many days

Please check if below points can narrow down the issue:
For v2 endpoint scope acts as resource . If the resource identifier
is omitted in the scope parameter, the resource is assumed to be
Microsoft Graph. If token is for Microsoft graph try by changing or
adding scope : User.Read . For example, scope=User.Read is
equivalent to https://graph.microsoft.com/User.Read and
offline_access is for refresh tokens Or try to Add the scope to
existing openid scope like scopes: []
For example:
scopes: ['openid', 'profile', email,'offline_access'], (or) scopes: ['openid', 'profile','offline_access']
Optional:Try also by giving client_secret inside the config
Make sure you have set the redirect url correctly.Add a trailing slash to redirect url to your config - e.g. msauth.BUNDLEID://auth/ - failure to add that may cause it to fail in IOS.
The cause may also be due to the user cancelling the operation in the middle of the process before authentication is completed.See Troubleshooting B2C | Microsoft Docs
References:
AppAuth iOS Token Exchange Problems Azure AD - Stack Overflow
Microsoft identity platform scopes, permissions, & consent | Microsoft Docs
react-native-app-auth (github.com)

Related

react-aad-masal token renewal issue

In one of my react project, I am using react-aad-msal for the authentication. But, it seems that I am having the following issue:
First time try to login and it works
After one hour the token expires and can't access the app
Need to clear the cache/browser history and re-run the react app again to access the page
Does anybody have experienced the similar issues. Here is the authProvider.js file looks like:
const config = {
auth: {
authority: `https://login.microsoftonline.com/${authority}`,
clientId,
validateAuthority: false,
redirectUri: window.location.origin,
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true,
},
};
const authenticationParameters = {
scopes: ['profile', 'offline_access'],
};
const options = {
loginType: LoginType.Redirect,
tokenRefreshUri: `${window.location.origin}/auth.html`,
};
Thanks in advance for the help.
• Please check for any conditional access policy that is assigned to your application authentication and sign in mechanism as if this policy is applied to your app’s service principal, your organization, or your application, then it will take precedence over the default values of refresh token timeout and issuance as well as access token also.
Thus, to check the authentication session controls for conditional access in Azure AD, please check the session control settings configured in Security --> conditional access as given below as these settings define the refresh token and session behavior: -
Also, ensure that certain settings in conditional access policy like Sign-in frequency control, persistent browser session control are correctly set or not enabled in your policy according to your requirement. Please find the reference images below for configuration of these settings: -
Please refer the below links for more details: -
https://learn.microsoft.com/en-us/azure/active-directory/conditional-access/howto-conditional-access-session-lifetime
https://learn.microsoft.com/en-us/azure/active-directory/conditional-access/concept-conditional-access-session

Error: AWS Web RTC Verification with Cognito

I am trying to connect my javascript app AWS WebRTC with a Cognito user to get its credentials dynamically but faced the following error code:
json.js:52 Uncaught (in promise) CredentialsError: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
I have done hard coding my credentials into the configuration and it has work successfully, however that's a bad practice hence I am trying to get AWS Web RTC credentials via my Cognito user. I have setup user pool and link in to my federal identities already. The credentials are now managed by AWS Amplify which loads AWS user profile from config file (./aws/credentials).
Following this two guides:
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-integrating-user-pools-with-identity-pools.html
https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html
I've written the following snippet to get my credentials but now faced the error.
AWS.config.region = '<REGION>';
AWS.config.update({
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: '<Region>:<IdentitiyPoolID>',
Logins: {
'cognito-idp.<Region>.amazonaws.com/<UserPoolID> ': <id token from cognito>,
},
}),
});
var accessKeyId;
var secretAccessKey;
AWS.config.credentials.get(function () {
accessKeyId = AWS.config.credentials.accessKeyId;
secretAccessKey = AWS.config.credentials.secretAccessKey;
});
const state = {
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'region',
}
async function startPlayerForViewer();
Any helps is much appreciated ! Cant find much updated resources/examples online.
credentials.get() is an async operation that receives the keys in a callback, while the state definition happens before that callback is received. Hence, the keys are not set. You need to ensure that you define the state after the callback and ensure that the connection happens afterwards.

Active Directory B2C Redirect URI With Angular App

We are using the MSAL service with an Angular App we built to use our AD B2C Login and Authentication.
The problem we are running into is that the Angular App has many routes, several of them are parameterized and can have n number of possibilities.
We set up the MSAL Service in our Angular like:
B2CAccessTokenKey = 'b2c.access.token';
tenantConfig = {
tenant: 'deepdivebioportal.onmicrosoft.com',
clientID: 'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
signInPolicy: 'B2C_1_signin',
signUpPolicy: 'B2C_1_signup',
redirectUri: 'https://xxx.yyyy.net',
b2cScopes: ['https://zzzzz.onmicrosoft.com/api/Hello.Read']
};
// Configure the authority for Azure AD B2C
authority = 'https://login.microsoftonline.com/tfp/' + this.tenantConfig.tenant + '/' + this.tenantConfig.signInPolicy;
/*
* B2C SignIn SignUp Policy Configuration
*/
clientApplication = new Msal.UserAgentApplication(
this.tenantConfig.clientID, this.authority,
function (errorDesc: any, token: any, error: any, tokenType: any) {
}
);
We are using Aquire Token Silently to refresh the token on refresh:
this.clientApplication.acquireTokenSilent(this.tenantConfig.b2cScopes);
We have added all our higher level routes to the App Setup Redirect URI's in Azure and if the user just happens to be on a route that is not explicitly in the list we get an error and can't refresh the token.
I have found many other questions asking similar questions and the solution seems to be to use wildcards in the redirect uri. However this no longer seems to be supported.
Is there a solution for this to handle n number of redirect routes?
The specific error I am getting:
main.b13cb77fd1caaf3b9027.js:1 ERROR Error: Uncaught (in promise): AADB2C90006: The redirect URI 'https://xxxxxx.yyyyyyy.zzz/ttttttt/show/23' provided in the request is not registered for the client id 'd86e217f-7a14-4cfc-b6ae-4f46a2eff943'.

Azure Web App with Acitve Directory Express with Graph API to get user photo

My Azure Web App has Active Directory enabled using the Express option. I can get the user claims/user's name from auth.me. How do I then get the user's photo/avatar? The token I get is not working in a Graph API call. I get this error from Graph API. Here is my code.
Please help! Spent hours searching and reading docs but nothing seems to address the Express AD scenario.
Thanks
Donnie
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: 80049217",
"innerError": {
"request-id": "e25f1fe5-4ede-4966-93c2-6d92d34da6ae",
"date": "2019-03-13T14:13:26"
}
}
}
axios.get('/.auth/me').then(resp => {
if(resp.data){
loggedInUser = {
accessToken:resp.data[0].access_token,
userId: resp.data[0].user_id,
username: resp.data[0].user_claims[9].val,
lastname: resp.data[0].user_claims[8].val,
fullname: resp.data[0].user_claims[11].val,
avatar:'https://cdn.vuetifyjs.com/images/lists/1.jpg'
}
let config = {
'headers':{
'Authorization': 'Bearer ' + loggedInUser.accessToken
}
}
axios.get('https://graph.microsoft.com/v1.0/me/photos/48x48/$value',config).then(resp => {
let photo = resp.data;
const url = window.URL || window.webkitURL;
const blobUrl = url.createObjectURL(photo);
document.getElementById('avatar').setAttribute("src", blobUrl);
loggedInUser.avatar = blobUrl;
console.log(blobUrl)
});
}
})
I was able to pull the image using MSDAL to handle the token. The new App Registration blade (as of 4/10/2019 is in preview) has a quick start which will ensure your app registration is correctly configure and allow you to download sample code.
In this blade, make sure you've added graph API permissions as shown below. When you click on Quick Start, you'll get a sample similar to this gist. It makes use of MSAL js library which handles the token negotiation.
var myMSALObj = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority,
acquireTokenRedirectCallBack, {
storeAuthStateInCookie: true,
cacheLocation: "localStorage"
});
function signIn() {
myMSALObj.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
//Login Success
showWelcomeMessage();
acquireTokenPopupAndCallMSGraph();
}, function (error) {
console.log(error);
});
}
After that, the magic happens in acquireTokenPopupAndCallMSGraph() which will acquire the token so you can use it to call the graph API. Now my gist makes use of XMLHttpRequest which I'm sure you'll be able to replace with axios.
To get the photo in the v1.0, it supports only a user's work or school mailboxes and not personal mailboxes.
For the details, you could read here.
Your AD app registration may not have the necessary delegate permissions. To add those permissions to your app, see these steps. I think you may need to use the oauth (login.microsoftonline.com/{{tenant}}/oauth2/v2.0/token) endpoint rather than .auth/me. With the oauth endpoint, you can even elect to pass in the scopes your token needs for calling the graph API. You can use http://jwt.ms to decode the token and see if has the necessary delegate permissions.
Also, I came across this blog series that lists various tutorials for working the Microsoft Graph. You can also check out https://github.com/microsoftgraph/nodejs-apponlytoken-rest-sample.
Furthermore, https://github.com/microsoftgraph/nodejs-connect-rest-sample makes use of passport and passport-azure-ad npm packages. That actually may be more advantagous to getting and managing tokens from Azure AD.
Hope this helps.
Ryan, I added delegate permissions to my web app's permissions settings for reading user profiles, but I still get the error message when tying to get profile pic from graph. Not sure what permissions it needs, but I basically gave it full access to use's profile. Graph just doesn't seem to like the token provided by AD Express config (login.microsoftonline.com)
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: 80049217",
"innerError": {
"request-id": "e25f1fe5-4ede-4966-93c2-6d92d34da6ae",
"date": "2019-03-13T14:13:26"
}
}
}
Ryan, jwt fails when I paste the full token from auth/me .

Refreshing token through msal.js

I'm using Azure AD B2C for my React.js app and I've noticed that after a while, all user requests are getting rejected by my API as unauthorized.
I'm pretty sure the issue is that the jwt token expires. I'm using msal.js to get my token from Azure AD B2C.
I found a short paragraph on Microsoft Docs but couldn't find any examples. Also my research indicates I need to open up a new windows and manually make an HTTP request. Is this correct?
Could someone tell me where I can find some examples of this?
Always call acquireTokenSilent before you call your API. Let MSAL do the caching, refreshing etc., that is what it is for. Fallback to AcquireTokenPopup or similar if silent fails.
https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp
function callApi() {
clientApplication.acquireTokenSilent(applicationConfig.b2cScopes).then(function (accessToken) {
callApiWithAccessToken(accessToken);
}, function (error) {
clientApplication.acquireTokenPopup(applicationConfig.b2cScopes).then(function (accessToken) {
callApiWithAccessToken(accessToken);
}, function (error) {
logMessage("Error acquiring the access token to call the Web api:\n" + error);
});
})
}
Side note: For acquireTokenSilent, MSAL is actually creating a hidden iframe to acquire the token, which might be what you are referring to in your question.

Resources