Skip to content

Update sample to follow Basher and Zero Trust #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 66 additions & 40 deletions 1-Authentication/2-sign-in-b2c/App/authConfig.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,82 @@
/**
* Configuration object to be passed to MSAL instance on creation.
* Enter here the user flows and custom policies for your B2C application
* To learn more about user flows, visit: https://docs.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview
* To learn more about custom policies, visit: https://docs.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-overview
*/
const b2cPolicies = {
names: {
signUpSignIn: 'B2C_1_susi_v2',
forgotPassword: 'B2C_1_reset_v3',
editProfile: 'B2C_1_edit_profile_v2',
},
authorities: {
signUpSignIn: {
authority: 'https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/B2C_1_susi_v2',
},
forgotPassword: {
authority: 'https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/B2C_1_reset_v3',
},
editProfile: {
authority: 'https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/B2C_1_edit_profile_v2',
},
},
authorityDomain: 'fabrikamb2c.b2clogin.com',
};

/**
* Configuration object to be passed to MSAL instance on creation.
* For a full list of MSAL.js configuration parameters, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
* For more details on MSAL.js and Azure AD B2C, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/working-with-b2c.md
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/working-with-b2c.md
*/

const msalConfig = {
auth: {
clientId: "2fdd06f3-7b34-49a3-a78b-0cf1dd87878e", // Replace with your AppID/ClientID obtained from Azure Portal.
authority: b2cPolicies.authorities.signUpSignIn.authority, // Choose sign-up/sign-in user-flow as your default.
knownAuthorities: [b2cPolicies.authorityDomain], // You must identify your tenant's domain as a known authority.
redirectUri: "http://localhost:6420", // You must register this URI on Azure Portal/App Registration. Defaults to "window.location.href".
postLogoutRedirectUri: "http://localhost:6420/signout", // Simply remove this line if you would like navigate to index page after logout.
navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
clientId: '2fdd06f3-7b34-49a3-a78b-0cf1dd87878e', // Replace with your AppID/ClientID obtained from Azure Portal.
authority: b2cPolicies.authorities.signUpSignIn.authority, // Choose sign-up/sign-in user-flow as your default.
knownAuthorities: [b2cPolicies.authorityDomain], // You must identify your tenant's domain as a known authority.
redirectUri: '/', // You must register this URI on Azure Portal/App Registration. Defaults to "window.location.href".
postLogoutRedirectUri: '/signout', // Simply remove this line if you would like navigate to index page after logout.
navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
},
cache: {
cacheLocation: "localStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO.
storeAuthStateInCookie: false, // If you wish to store cache items in cookies as well as browser cache, set this to "true".
cacheLocation: 'localStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO.
storeAuthStateInCookie: false, // If you wish to store cache items in cookies as well as browser cache, set this to "true".
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
},
},
},
};

/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
* For more information about OIDC scopes, visit:
* For more information about OIDC scopes, visit:
* https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
const loginRequest = {
scopes: ["openid", "offline_access"],
scopes: ['openid', 'offline_access'],
};

/**
Expand All @@ -66,7 +91,8 @@ const loginRequest = {

// exporting config object for jest
if (typeof exports !== 'undefined') {
module.exports = {
msalConfig: msalConfig,
};
}
module.exports = {
msalConfig: msalConfig,
b2cPolicies: b2cPolicies,
};
}
189 changes: 129 additions & 60 deletions 1-Authentication/2-sign-in-b2c/App/authPopup.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,74 @@
// configuration parameters are located at authConfig.js
const myMSALObj = new msal.PublicClientApplication(msalConfig);

let accountId = "";
let username = "";
let accountId = '';
let username = '';

myMSALObj.addEventCallback((event) => {
console.log(event.eventType);
if (
(event.eventType === msal.EventType.LOGIN_SUCCESS ||
event.eventType === msal.EventType.ACQUIRE_TOKEN_SUCCESS) &&
event.payload.account
) {
/**
* For the purpose of setting an active account for UI update, we want to consider only the auth
* response resulting from SUSI flow. "tfp" claim in the id token tells us the policy (NOTE: legacy
* policies may use "acr" instead of "tfp"). To learn more about B2C tokens, visit:
* https://docs.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview
*/

if (event.payload.idTokenClaims['tfp'] === b2cPolicies.names.editProfile) {
const originalSignInAccount = myMSALObj
.getAllAccounts()
.find(
(account) =>
account.idTokenClaims.oid === event.payload.idTokenClaims.oid &&
account.idTokenClaims.sub === event.payload.idTokenClaims.sub &&
account.idTokenClaims['tfp'] === b2cPolicies.names.signUpSignIn
);

let signUpSignInFlowRequest = {
authority: b2cPolicies.authorities.signUpSignIn.authority,
account: originalSignInAccount,
};

// silently login again with the signUpSignIn policy
myMSALObj.ssoSilent(signUpSignInFlowRequest).catch((error) => {
console.log(error);
if (error instanceof msal.InteractionRequiredAuthError) {
myMSALObj.loginPopup({
...signUpSignInFlowRequest,
});
}
});
}

function selectAccount () {
/**
* Below we are checking if the user is returning from the reset password flow.
* If so, we will ask the user to reauthenticate with their new password.
* If you do not want this behavior and prefer your users to stay signed in instead,
* you can replace the code below with the same pattern used for handling the return from
* profile edit flow
*/

if (event.payload.idTokenClaims['tfp'] === b2cPolicies.names.forgotPassword) {
let signUpSignInFlowRequest = {
authority: b2cPolicies.authorities.signUpSignIn.authority,
};
myMSALObj
.loginPopup(signUpSignInFlowRequest)
.then(handleResponse)
.catch((error) => {
console.log(error);
});
}
}
});

function selectAccount() {
/**
* See here for more info on account retrieval:
* See here for more info on account retrieval:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
*/

Expand All @@ -18,22 +79,42 @@ function selectAccount () {
return;
} else if (currentAccounts.length > 1) {
// Add your account choosing logic here
console.log("Multiple accounts detected.");
console.log('Multiple accounts detected.');

const originalSignInAccount = myMSALObj
.getAllAccounts()
.find((account) => account.idTokenClaims['tfp'] === b2cPolicies.names.signUpSignIn);

accountId = originalSignInAccount.homeAccountId;

username = originalSignInAccount.username ? originalSignInAccount.username : originalSignInAccount.name;
welcomeUser(username);
myMSALObj
.acquireTokenSilent({
account: myMSALObj.getAccountByHomeId(accountId),
scopes: ['openid'],
})
.then((response) => {
updateTable(response.idTokenClaims);
});

} else if (currentAccounts.length === 1) {
accountId = currentAccounts[0].homeAccountId;
username = currentAccounts[0].username;
welcomeUser(username);

/**
* In order to obtain the ID Token in the cached obtained previously, you can initiate a
* silent token request by passing the current user's account and the scope "openid".
*/
myMSALObj.acquireTokenSilent({
account: myMSALObj.getAccountByHomeId(accountId),
scopes: ["openid"]
}).then(response => {
updateTable(response.idTokenClaims)
});
* In order to obtain the ID Token in the cached obtained previously, you can initiate a
* silent token request by passing the current user's account and the scope "openid".
*/
myMSALObj
.acquireTokenSilent({
account: myMSALObj.getAccountByHomeId(accountId),
scopes: ['openid'],
})
.then((response) => {
updateTable(response.idTokenClaims);
});
}
}

Expand All @@ -57,99 +138,87 @@ function handleResponse(response) {
}

function signIn() {

/**
* You can pass a custom request object below. This will override the initial configuration. For more information, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
*/

myMSALObj.loginPopup(loginRequest)
myMSALObj
.loginPopup({
...loginRequest,
})
.then(handleResponse)
.catch(error => {
.catch((error) => {
console.log(error);

// Error handling
if (error.errorMessage) {
// Check for forgot password error
// Learn more about AAD error codes at https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
if (error.errorMessage.indexOf("AADB2C90118") > -1) {
myMSALObj.loginPopup(b2cPolicies.authorities.forgotPassword)
.then(response => handlePolicyChange(response));
if (error.errorMessage.indexOf('AADB2C90118') > -1) {
myMSALObj.loginPopup(b2cPolicies.authorities.forgotPassword);
}
}
});
}

function signOut() {

/**
* You can pass a custom request object below. This will override the initial configuration. For more information, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
*/

// Choose which account to logout from.

const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId)
mainWindowRedirectUri: 'http://localhost:6420/signout',
redirectUri: '/redirect',
};
myMSALObj.logout(logoutRequest);

myMSALObj.logoutPopup(logoutRequest);
}

function getTokenPopup(request) {

/**
* See here for more information on account retrieval:
/**
* See here for more information on account retrieval:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
*/

request.account = myMSALObj.getAccountByHomeId(accountId);

return myMSALObj.acquireTokenSilent(request)

return myMSALObj
.acquireTokenSilent(request)
.then((response) => {
// In case the response from B2C server has an empty accessToken field
// throw an error to initiate token acquisition
if (!response.accessToken || response.accessToken === "") {
throw new msal.InteractionRequiredAuthError;
if (!response.accessToken || response.accessToken === '') {
throw new msal.InteractionRequiredAuthError();
}
return response;
})
.catch(error => {
.catch((error) => {
console.log(error);
console.log("silent token acquisition fails. acquiring token using popup");
console.log('silent token acquisition fails. acquiring token using popup');
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
return myMSALObj.acquireTokenPopup(request)
.then(response => {
return myMSALObj
.acquireTokenPopup({
...request,
redirectUri: '/redirect',
})
.then((response) => {
console.log(response);
return response;
}).catch(error => {
})
.catch((error) => {
console.log(error);
});
} else {
console.log(error);
console.log(error);
}
});
});
}

function editProfile() {
myMSALObj.loginPopup(b2cPolicies.authorities.editProfile)
.then(response => handlePolicyChange(response));
}

function handlePolicyChange(response) {

/**
* We need to reject id tokens that were not issued with the default sign-in policy.
* "acr" claim in the token tells us what policy is used (NOTE: for new policies (v2.0), use "tfp" instead of "acr").
* To learn more about B2C tokens, visit https://docs.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview
*/

if (response.idTokenClaims['acr'] === b2cPolicies.names.editProfile) {
window.alert("Profile has been updated successfully. \nPlease sign-in again.");
myMSALObj.logout();
} else if (response.idTokenClaims['acr'] === b2cPolicies.names.forgotPassword) {
window.alert("Password has been reset successfully. \nPlease sign-in with your new password.");
myMSALObj.logout();
}
myMSALObj.loginPopup({
...b2cPolicies.authorities.editProfile,
});
}
Loading