react-aad-masal token renewal issue - reactjs

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

Related

InteractionRequiredAuthError: invalid_grant: AADSTS50076

Error message: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access 'bxxx-xxxx-xxxxa'.
I am getting this error intermittently, while accessing token with auth code.
Token endpoint fails with error code 400.
Request body in browser contains:
POST: https://login.microsoftonline.com/tenantID/oauth2/v2.0/token
clientId,
scope - xxxxxxxx/.default openid profile offline_access
grant_type: authorization_code
code
redirect_uri
and here is MSAL configuration: (we are using react-msal 1.4.3)
const msalConfig = {
auth: {
clientId: env?.ClientId,
authority: env?.Authority,
redirectUri: env?.RedirectUri,
postLogoutRedirectUri: env?.PostLogoutRedirectUri,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true,
},
scopes: [env?.AuthScope],
}
Please let me know if anyone has encounter this issue before and found any solution for it.
• It is because your administrator has enabled the security defaults setting in ‘Manage security defaults’ section in Azure AD tenant properties as shown below in the snapshot. When you enable this option, Azure AD mandates all users to register for Azure AD multi-factor authentication, requires the same for administrators and enforces it, blocks legacy authentication protocols, and protects privileged activities like access to the Azure portal.
Thus, if you are assigned a role of ‘Administrator’ of any sort, i.e., Global, Authentication, Application, Billing, Exchange, etc., then your ID would be required to do multi-factor authentication. Also, please ensure that you are not using any older protocol and legacy authentication since those doesn’t have access to multi-factor authentication.
As a result, this would help in resolving the issue and the subsequent error that you are facing. For more information, kindly refer to the below links given: -
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults
https://learn.microsoft.com/en-us/answers/questions/494959/aadsts50076-ue-to-a-configuration-change-made-by-y.html

React Native, unable to get access token

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)

Is it possible to implement switch account feature using msal.js for SPA website?

I am trying to implement switch account feature for my SPA website. I am able to login an account that matches the current user that launched the browser. But if i prompt for account selection and provide a different account email id to login then it still using the current user that launched the browser to login and retrieves the id token. I have a service account that i would like to use but am not able to get token for the service user account from my actual windows account browser instance. Both of these accounts are in same tenant (company tenant) and i can log them in if i launch the browser (Run as User feature) with the corresponding windows Account. Is it possible to implement switch account using msal.js 1.2.2 version? if yes, can i get a sample on how to implement the feature?
The below is my msal config
var msalConfig = {
auth: {
clientId: config.appServiceConfig.clientId,
authority: config.appServiceConfig.authority,
redirectURI: config.appServiceConfig.redirectURI,
navigateToLoginRequestUrl: false
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true
}
};
var requestObj = {
scopes: ["User.ReadBasic.All"],
prompt: "select_account",
loginHint: "serviceaccount#xxx.com",
authority: config.appServiceConfig.authority
};
Appreciate any help!!!
Thanks
Sarat.

The Reply URL specified in the request does not match the reply URL's configured for the application

I am currently using Microsoft adal angular for Azure active directory authentication and below if the configuration settings for the same.
MsAdalAngular6Module.forRoot({
tenant: 'xxxxxxxxxxxxxxxxxxx',
clientId: 'xxxxxxxxxxxxxxxxx',
redirectUri: window.location.origin,
endpoints: {
"xxxxxxxx": "xxxxxxxxxxxxxx",
},
navigateToLoginRequestUrl: true,
cacheLocation: 'localStorage',
loadFrameTimeout: 60000
}),
I have set reply URL as https://xxx.azurewebsites.net/ in Azure app registrations.
The above configuration works fine if I use https://xxx.azurewebsites.net/ and enter into the application. But when I use https://xxx.azurewebsites.net/dashboard and enter my credentials it is throwing the error mentioned in the subject and not allowing me to go in.
I know that the Azure has blocked wild card configurations in Active directory. Is there a way for me to configure the settings to successfully authenticate If I copy-paste any deep link from the application.
Any help would be really appreciated and thanks in advance.
When the redirect_uri in the authorization request mismatches the redirect url configured in Azure AD registrations, you will encounter this error.
So if you want to use https://xxx.azurewebsites.net/dashboard in your request, you should also add it as the redirect url of your Azure AD registrations.
Update:
Based on our discussion, you just need to specify the redirect URL in your code as the same url as what you have configured in your Azure AD app: https://xxx.azurewebsites.net to meet your requirement.

Cannot Authenticate SPA with passport-azure-ad's Bear Strategy

So I was playing get Integrating Azure AD into an AngularJS single page app
this tutorial to work.
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-devquickstarts-angular-node
It is implemented for the Azure AD v2.0 endpoint, but unfortunately my organization does not support the Azure AD v2.0 endpoint, therefore I replaced the experimental version of adal.js and adal-angular libraries with GA adal.js and adal-angularlibraries. The front-end authentication works perfect. However after I modified the back-end config based on passport-azure-ad. The back-end failed to authenticate the tokens that was implicitly granted.
I have set the allow implicit flow to true in the manifest file. Also I tried to use my client ID and Tenant Name in another example that uses the same angular front end but .NET as the back-end. It worked!
Here is my back-end config
exports.creds = {
// The app id you get from the registration portal
audience: 'http://localhost:8080',
clientID: '**********************************',
// Passport will use this URL to fetch the token validation information from Azure AD
identityMetadata: '************************************',
// Required.
// If you are using the common endpoint, you should either set `validateIssuer` to false, or provide a value for `issuer`.
validateIssuer: true,
// Required.
// Set to true if you use `function(req, token, done)` as the verify callback.
// Set to false if you use `function(req, token)` as the verify callback.
passReqToCallback: false,
// Required if you are using common endpoint and setting `validateIssuer` to true.
// For tenant-specific endpoint, this field is optional, we will use the issuer from the metadata by default.
issuer: '**************************************',
isB2C: false,
// Optional. Default value is false.
// Set to true if you accept access_token whose `aud` claim contains multiple values.
allowMultiAudiencesInToken: false,
// Optional. 'error', 'warn' or 'info'
loggingLevel: 'info'
};
My server:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Pull in the Azure AD bearer passport strategy
var OIDCBearerStrategy = require('passport-azure-ad').BearerStrategy;
// This object is used for in-memory data storage, instead of a database.
// Each time you run the server, you will get a fresh, empty list.
var tasks = [];
// Load passport and configure it to use Azure AD Bearer auth
app.use(passport.initialize());
passport.use(new OIDCBearerStrategy({
identityMetadata: config.creds.identityMetadata,
audience: config.creds.audience,
clientID: config.creds.clientID,
validateIssuer: true,
issuer: config.creds.issuer,
}, function (token, done) {
console.log("yooo");
return done(null, token, null);
}));
var router = express.Router();
router.route('/api/tasks')
.post(passport.authenticate('oauth-bearer', { session: false }), controller)
Here is the output from my browser console after the front-end authenticated:
State: **************
adal.js:973 State status:true
adal.js:973 State is right
Has anybody done similar things?
As mentioned in the comment above by the Author of this question, the audience value in the config should be the client ID.
If anybody have trouble getting it started with Angularjs1 + Nodejs + adal.js v1.x
Here is an working example. Just change the values in the config.js and app.js
https://github.com/lightertu/Azure-ActiveDirectory-V1-Angularjs-Nodejs-SPA-Sample

Resources