-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add msal-browser, obtain a token from AzureAD and invoke the Api with…
… the token
- Loading branch information
Showing
4 changed files
with
70 additions
and
5 deletions.
There are no files selected for viewing
16 changes: 16 additions & 0 deletions
16
web/msal-2-auth-code-flow-spa-aspnet-core-31/Msal2/ClientApp/package-lock.json
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
web/msal-2-auth-code-flow-spa-aspnet-core-31/Msal2/ClientApp/src/components/auth.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import * as msal from "@azure/msal-browser"; | ||
|
||
const msalConfig = { | ||
auth: { | ||
clientId: "<Client ID of your app registration>", | ||
authority: "https://login.microsoftonline.com/common/", | ||
redirectUri: "<your redirect URI i.e. https://localhost:44317>", | ||
} | ||
}; | ||
const loginRequest = { | ||
scopes: ["someApiScope"] | ||
}; | ||
|
||
const myMSALObj = new msal.PublicClientApplication(msalConfig); | ||
|
||
class Auth { | ||
async getToken() { | ||
try { | ||
const tokenRequest = { | ||
account: myMSALObj.getAllAccounts()[0], | ||
scopes: ["someApiScope"] | ||
}; | ||
const tokenResponse = await myMSALObj.acquireTokenSilent(tokenRequest); | ||
return tokenResponse.accessToken; | ||
} | ||
catch (err1) { | ||
try { | ||
await myMSALObj.loginRedirect(loginRequest); | ||
} catch (err2) { | ||
console.error(err2); | ||
} | ||
} | ||
} | ||
} | ||
|
||
const auth = new Auth(); | ||
export default auth; | ||
|
||
myMSALObj.handleRedirectPromise().then((tokenResponse) => { | ||
if (tokenResponse !== null) { | ||
console.log("Authenticated!") | ||
} | ||
}).catch((error) => { | ||
console.error(error); | ||
}); |