Skip to content

Commit

Permalink
add msal-browser, obtain a token from AzureAD and invoke the Api with…
Browse files Browse the repository at this point in the history
… the token
  • Loading branch information
bnek committed Oct 29, 2020
1 parent b77263c commit c8d55d4
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 5 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@azure/msal-browser": "^2.1.0",
"bootstrap": "^4.1.3",
"jquery": "^3.4.1",
"merge": "^1.2.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { Component } from 'react';
import auth from './auth';

export class Home extends Component {
constructor(props) {
Expand All @@ -7,10 +8,12 @@ export class Home extends Component {
}

fetchWeather() {
fetch("/weatherforecast").then(response => {
response.json().then(result => {
this.setState(result);
})
auth.getToken().then(accessToken => {
fetch("/weatherforecast", { headers: { Authorization: `Bearer ${accessToken}` } }).then(response => {
response.json().then(result => {
this.setState(result);
})
});
});
}

Expand All @@ -20,7 +23,7 @@ export class Home extends Component {
<div>
<h1>Tomorrow's weather forecast</h1>
<br />
<button onClick={() => this.fetchWeather() }>refresh</button>
<button onClick={() => this.fetchWeather()}>refresh</button>
<br />
{weather &&
<div>
Expand Down
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);
});

0 comments on commit c8d55d4

Please sign in to comment.