MSAL 2.0 checkpoint

This commit is contained in:
Steve Faulkner
2020-12-28 18:48:19 -06:00
parent 13dbcb6453
commit 12a44fdd42
10 changed files with 2103 additions and 2141 deletions

File diff suppressed because it is too large Load Diff

23
package-lock.json generated
View File

@@ -15328,6 +15328,15 @@
"tinyqueue": "^1.1.0"
}
},
"match-sorter": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/match-sorter/-/match-sorter-6.0.2.tgz",
"integrity": "sha512-SDRLNlWof9GnAUEyhKP0O5525MMGXUGt+ep4MrrqQ2StAh3zjvICVZseiwg7Zijn3GazpJDiwuRr/mFDHd92NQ==",
"requires": {
"@babel/runtime": "^7.12.5",
"remove-accents": "0.4.2"
}
},
"matchdep": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/matchdep/-/matchdep-2.0.0.tgz",
@@ -17775,6 +17784,15 @@
"warning": "^4.0.2"
}
},
"react-query": {
"version": "3.5.5",
"resolved": "https://registry.npmjs.org/react-query/-/react-query-3.5.5.tgz",
"integrity": "sha512-WYZcHcAs5K5lPGT6CI8fz3lU62S8IfZhvB1K4aZH27wg9T6CWei+y7IRyZwti9X18LX134O4olgEuNth9LEX+w==",
"requires": {
"@babel/runtime": "^7.5.5",
"match-sorter": "^6.0.2"
}
},
"react-redux": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.1.3.tgz",
@@ -18167,6 +18185,11 @@
"superagent-proxy": "^2.0.0"
}
},
"remove-accents": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/remove-accents/-/remove-accents-0.4.2.tgz",
"integrity": "sha1-CkPTqq4egNuRngeuJUsoXZ4ce7U="
},
"remove-trailing-separator": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz",

View File

@@ -85,6 +85,7 @@
"react-dom": "16.9.0",
"react-hotkeys": "2.0.0",
"react-notification-system": "0.2.17",
"react-query": "3.5.5",
"react-redux": "7.1.3",
"redux": "4.0.4",
"rx-jupyter": "5.5.12",

View File

@@ -1,4 +1,3 @@
import { AuthType } from "../../../AuthType";
import { StyleConstants } from "../../../Common/Constants";
import { DatabaseAccount, Subscription } from "../../../Contracts/DataModels";
@@ -6,172 +5,136 @@ import * as React from "react";
import { DefaultButton, IButtonStyles, IButtonProps } from "office-ui-fabric-react/lib/Button";
import { IContextualMenuProps } from "office-ui-fabric-react/lib/ContextualMenu";
import { Dropdown, IDropdownOption, IDropdownProps } from "office-ui-fabric-react/lib/Dropdown";
import { useSubscriptions } from "../../../hooks/useSubscriptions";
export interface AccountSwitchComponentProps {
authType: AuthType;
selectedAccountName: string;
accounts: DatabaseAccount[];
isLoadingAccounts: boolean;
onAccountChange: (newAccount: DatabaseAccount) => void;
selectedSubscriptionId: string;
subscriptions: Subscription[];
isLoadingSubscriptions: boolean;
onSubscriptionChange: (newSubscription: Subscription) => void;
displayText?: string;
}
export class AccountSwitchComponent extends React.Component<AccountSwitchComponentProps> {
public render(): JSX.Element {
return this.props.authType === AuthType.AAD ? this._renderSwitchDropDown() : this._renderAccountName();
}
private _renderSwitchDropDown(): JSX.Element {
const { displayText, selectedAccountName } = this.props;
const menuProps: IContextualMenuProps = {
directionalHintFixed: true,
className: "accountSwitchContextualMenu",
items: [
{
key: "switchSubscription",
onRender: this._renderSubscriptionDropdown.bind(this)
},
{
key: "switchAccount",
onRender: this._renderAccountDropDown.bind(this)
}
]
};
const buttonStyles: IButtonStyles = {
root: {
fontSize: StyleConstants.DefaultFontSize,
height: 40,
padding: 0,
paddingLeft: 10,
marginRight: 5,
backgroundColor: StyleConstants.BaseDark,
color: StyleConstants.BaseLight
export const AccountSwitchComponent: React.FunctionComponent = () => {
const subscriptions = useSubscriptions();
const menuProps: IContextualMenuProps = {
directionalHintFixed: true,
className: "accountSwitchContextualMenu",
items: [
{
key: "switchSubscription",
onRender: () => renderSubscriptionDropdown(subscriptions)
},
rootHovered: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootFocused: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootPressed: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootExpanded: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
textContainer: {
flexGrow: "initial"
{
key: "switchAccount",
onRender: renderAccountDropDown
}
};
const buttonProps: IButtonProps = {
text: displayText || selectedAccountName,
menuProps: menuProps,
styles: buttonStyles,
className: "accountSwitchButton",
id: "accountSwitchButton"
};
return <DefaultButton {...buttonProps} />;
}
private _renderSubscriptionDropdown(): JSX.Element {
const { subscriptions, selectedSubscriptionId, isLoadingSubscriptions } = this.props;
const options: IDropdownOption[] = subscriptions.map(sub => {
return {
key: sub.subscriptionId,
text: sub.displayName,
data: sub
};
});
const placeHolderText = isLoadingSubscriptions
? "Loading subscriptions"
: !options || !options.length
? "No subscriptions found in current directory"
: "Select subscription from list";
const dropdownProps: IDropdownProps = {
label: "Subscription",
className: "accountSwitchSubscriptionDropdown",
options: options,
onChange: this._onSubscriptionDropdownChange,
defaultSelectedKey: selectedSubscriptionId,
placeholder: placeHolderText,
styles: {
callout: "accountSwitchSubscriptionDropdownMenu"
}
};
return <Dropdown {...dropdownProps} />;
}
private _onSubscriptionDropdownChange = (e: React.FormEvent<HTMLDivElement>, option: IDropdownOption): void => {
if (!option) {
return;
}
this.props.onSubscriptionChange(option.data);
]
};
private _renderAccountDropDown(): JSX.Element {
const { accounts, selectedAccountName, isLoadingAccounts } = this.props;
const options: IDropdownOption[] = accounts.map(account => {
return {
key: account.name,
text: account.name,
data: account
};
});
// Fabric UI will also try to select the first non-disabled option from dropdown.
// Add a option to prevent pop the message when user click on dropdown on first time.
options.unshift({
key: "select from list",
text: "Select Cosmos DB account from list",
data: undefined
});
const placeHolderText = isLoadingAccounts
? "Loading Cosmos DB accounts"
: !options || !options.length
? "No Cosmos DB accounts found"
: "Select Cosmos DB account from list";
const dropdownProps: IDropdownProps = {
label: "Cosmos DB Account Name",
className: "accountSwitchAccountDropdown",
options: options,
onChange: this._onAccountDropdownChange,
defaultSelectedKey: selectedAccountName,
placeholder: placeHolderText,
styles: {
callout: "accountSwitchAccountDropdownMenu"
}
};
return <Dropdown {...dropdownProps} />;
}
private _onAccountDropdownChange = (e: React.FormEvent<HTMLDivElement>, option: IDropdownOption): void => {
if (!option) {
return;
const buttonStyles: IButtonStyles = {
root: {
fontSize: StyleConstants.DefaultFontSize,
height: 40,
padding: 0,
paddingLeft: 10,
marginRight: 5,
backgroundColor: StyleConstants.BaseDark,
color: StyleConstants.BaseLight
},
rootHovered: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootFocused: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootPressed: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootExpanded: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
textContainer: {
flexGrow: "initial"
}
this.props.onAccountChange(option.data);
};
private _renderAccountName(): JSX.Element {
const { displayText, selectedAccountName } = this.props;
return <span className="accountNameHeader">{displayText || selectedAccountName}</span>;
}
const buttonProps: IButtonProps = {
text: "foo",
menuProps: menuProps,
styles: buttonStyles,
className: "accountSwitchButton",
id: "accountSwitchButton"
};
return <DefaultButton {...buttonProps} />;
};
function renderSubscriptionDropdown(subscriptions: Subscription[]): JSX.Element {
const selectedSubscriptionId = "";
const isLoadingSubscriptions = false;
const options: IDropdownOption[] = subscriptions.map(sub => {
return {
key: sub.subscriptionId,
text: sub.displayName,
data: sub
};
});
const placeHolderText = isLoadingSubscriptions
? "Loading subscriptions"
: !options || !options.length
? "No subscriptions found in current directory"
: "Select subscription from list";
const dropdownProps: IDropdownProps = {
label: "Subscription",
className: "accountSwitchSubscriptionDropdown",
options: options,
onChange: () => {},
defaultSelectedKey: selectedSubscriptionId,
placeholder: placeHolderText,
styles: {
callout: "accountSwitchSubscriptionDropdownMenu"
}
};
return <Dropdown {...dropdownProps} />;
}
function renderAccountDropDown(): JSX.Element {
const accounts = [];
const selectedAccountName = "foo";
const isLoadingAccounts = false;
const options: IDropdownOption[] = accounts.map(account => {
return {
key: account.name,
text: account.name,
data: account
};
});
// Fabric UI will also try to select the first non-disabled option from dropdown.
// Add a option to prevent pop the message when user click on dropdown on first time.
options.unshift({
key: "select from list",
text: "Select Cosmos DB account from list",
data: undefined
});
const placeHolderText = isLoadingAccounts
? "Loading Cosmos DB accounts"
: !options || !options.length
? "No Cosmos DB accounts found"
: "Select Cosmos DB account from list";
const dropdownProps: IDropdownProps = {
label: "Cosmos DB Account Name",
className: "accountSwitchAccountDropdown",
options: options,
onChange: () => {},
defaultSelectedKey: selectedAccountName,
placeholder: placeHolderText,
styles: {
callout: "accountSwitchAccountDropdownMenu"
}
};
return <Dropdown {...dropdownProps} />;
}

View File

@@ -1,5 +1,5 @@
import { Configuration, PublicClientApplication } from "@azure/msal-browser";
import { AuthenticatedTemplate, MsalProvider, UnauthenticatedTemplate } from "@azure/msal-react";
import { AuthenticatedTemplate, MsalProvider, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";
import { useBoolean } from "@uifabric/react-hooks";
import {
DefaultButton,
@@ -15,30 +15,51 @@ import * as React from "react";
import { render } from "react-dom";
import FeedbackIcon from "../images/Feedback.svg";
import ConnectIcon from "../images/HostedConnectwhite.svg";
import ChevronRight from "../images/chevron-right.svg";
import "../less/hostedexplorer.less";
import { AccountSwitchComponent } from "./Explorer/Controls/AccountSwitch/AccountSwitchComponent";
import { CommandButtonComponent } from "./Explorer/Controls/CommandButton/CommandButtonComponent";
import { DefaultDirectoryDropdownComponent } from "./Explorer/Controls/Directory/DefaultDirectoryDropdownComponent";
import { DirectoryListComponent } from "./Explorer/Controls/Directory/DirectoryListComponent";
import "./Explorer/Menus/NavBar/MeControlComponent.less";
import { useGraphProfile } from "./hooks/useGraphProfile";
import { useGraphPhoto } from "./hooks/useGraphPhoto";
import { ConnectScreen } from "./Platform/Hosted/ConnectScreen";
import "./Shared/appInsights";
import { useAADAccount } from "./hooks/useAADAccount";
initializeIcons();
// MSAL configuration
const configuration: Configuration = {
auth: {
clientId: "e8ae3d28-de2a-4dc8-8fa3-2d2998b1c38f",
clientId: "203f1145-856a-4232-83d4-a43568fba23d",
redirectUri: "https://localhost:1234/hostedExplorer.html",
authority: "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47"
authority: "https://login.windows-ppe.net/common"
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false
}
};
// const configuration: Configuration = {
// auth: {
// clientId: "b4d07291-7936-4c8e-b413-f58b6d1c67e8",
// redirectUri: "https://localhost:1234/hostedExplorer.html",
// authority: "https://login.microsoftonline.com/907765e9-1846-4d84-ad7f-a2f5030ef5ba"
// },
// cache: {
// cacheLocation: "sessionStorage"
// }
// };
const application = new PublicClientApplication(configuration);
const App: React.FunctionComponent = () => {
const [isOpen, { setTrue: openPanel, setFalse: dismissPanel }] = useBoolean(false);
const { graphData, photo } = useGraphProfile();
const { instance } = useMsal();
const account = useAADAccount();
const photo = useGraphPhoto();
const menuProps = {
className: "mecontrolContextualMenu",
@@ -123,23 +144,18 @@ const App: React.FunctionComponent = () => {
<div className="cosmosDBTitle">
<span
className="title"
data-bind="click: openAzurePortal, event: { keypress: onOpenAzurePortalKeyPress }"
onClick={() => window.open("https://portal.azure.com", "_blank")}
tabIndex={0}
title="Go to Azure Portal"
>
Microsoft Azure
</span>
<span className="accontSplitter" /> <span className="serviceTitle">Cosmos DB</span>
<img
className="chevronRight"
src="/chevron-right.svg"
alt="account separator"
data-bind="visible: isAccountActive"
/>
<span
className="accountSwitchComponentContainer"
data-bind="react: accountSwitchComponentAdapter, visible: isAccountActive"
/>
<img className="chevronRight" src={ChevronRight} alt="account separator" />
<span className="accountSwitchComponentContainer">
{/* <AccountSwitchComponent /> */}
<span className="accountNameHeader">REPLACE ME - Connection string mode</span>;
</span>
</div>
<div className="feedbackConnectSettingIcons">
<AuthenticatedTemplate>
@@ -177,8 +193,8 @@ const App: React.FunctionComponent = () => {
<DefaultButton {...buttonProps}>
<Persona
imageUrl={photo}
text={graphData?.displayName}
secondaryText={graphData?.displayName}
text={account?.name}
secondaryText={account?.username}
showSecondaryText={true}
showInitialsUntilImageLoads={true}
initialsColor={PersonaInitialsColor.teal}
@@ -193,7 +209,10 @@ const App: React.FunctionComponent = () => {
className="mecontrolSigninButton"
text="Sign In"
onClick={() => {
instance.loginPopup();
instance.loginPopup({
scopes: ["https://graph.microsoft-ppe.com/" + "/.default"],
redirectUri: "https://localhost:1234/hostedExplorer.html"
});
}}
styles={{
rootHovered: { backgroundColor: "#393939", color: "#fff" },
@@ -205,30 +224,30 @@ const App: React.FunctionComponent = () => {
</div>
</div>
</header>
{/* <iframe
id="explorerMenu"
name="explorer"
className="iframe"
title="explorer"
src="explorer.html?v=1.0.1&platform=Hosted"
data-bind="visible: navigationSelection() === 'explorer'"
></iframe> */}
<AuthenticatedTemplate>
<p>LOGGED IN!</p>
{/* <iframe
id="explorerMenu"
name="explorer"
className="iframe"
title="explorer"
src="explorer.html?v=1.0.1&platform=Portal"
></iframe> */}
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<ConnectScreen />
</UnauthenticatedTemplate>
<ConnectScreen />
<div data-bind="react: firewallWarningComponentAdapter" />
<div data-bind="react: dialogComponentAdapter" />
<Panel
headerText="Select Directory"
isOpen={!isOpen}
onDismiss={dismissPanel}
// You MUST provide this prop! Otherwise screen readers will just say "button" with no label.
closeButtonAriaLabel="Close"
>
<div className="directoryDropdownContainer">
<Panel headerText="Select Directory" isOpen={isOpen} onDismiss={dismissPanel} closeButtonAriaLabel="Close">
{/* <div className="directoryDropdownContainer">
<DefaultDirectoryDropdownComponent />
</div>
<div className="directoryDivider" />
<div className="directoryListContainer">
<DirectoryListComponent />
</div>
</div> */}
</Panel>
</div>
);

View File

@@ -6,7 +6,7 @@ import { configContext } from "../../ConfigContext";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
// TODO: 421864 - add a fetch wrapper
export abstract class ArmResourceUtils {
export class ArmResourceUtils {
private static readonly _armEndpoint: string = configContext.ARM_ENDPOINT;
private static readonly _armApiVersion: string = configContext.ARM_API_VERSION;
private static readonly _armAuthArea: string = configContext.ARM_AUTH_AREA;

View File

@@ -20,20 +20,7 @@ export default class AuthHeadersUtil {
private static readonly _graphEndpoint: string = configContext.GRAPH_ENDPOINT;
private static readonly _graphApiVersion: string = configContext.GRAPH_API_VERSION;
private static _authContext: AuthenticationContext = new AuthenticationContext({
instance: AuthHeadersUtil._aadEndpoint,
clientId: AuthHeadersUtil._firstPartyAppId,
postLogoutRedirectUri: window.location.origin,
endpoints: {
aad: AuthHeadersUtil._aadEndpoint,
graph: AuthHeadersUtil._graphEndpoint,
armAuthArea: AuthHeadersUtil._armAuthArea,
armEndpoint: AuthHeadersUtil._armEndpoint,
arcadiaEndpoint: AuthHeadersUtil._arcadiaEndpoint
},
tenant: undefined,
cacheLocation: window.navigator.userAgent.indexOf("Edge") > -1 ? "localStorage" : undefined
});
private static _authContext: any = {};
public static getAccessInputMetadata(accessInput: string): Q.Promise<DataModels.AccessInputMetadata> {
const deferred: Q.Deferred<DataModels.AccessInputMetadata> = Q.defer<DataModels.AccessInputMetadata>();

View File

@@ -1,7 +1,7 @@
import { useAccount, useMsal } from "@azure/msal-react";
import { useEffect, useState } from "react";
import { useAADToken } from "./useAADToken";
export async function fetchMe(accessToken: string): Promise<GraphMeResponse> {
export async function fetchMe(accessToken: string): Promise<ProfileResponse> {
const headers = new Headers();
const bearer = `Bearer ${accessToken}`;
@@ -12,32 +12,12 @@ export async function fetchMe(accessToken: string): Promise<GraphMeResponse> {
headers: headers
};
console.log("EXECUTING REQUEST");
return fetch("https://graph.microsoft.com/v1.0/me", options)
.then(response => response.json())
.catch(error => console.log(error));
}
export async function fetchPhoto(accessToken: string): Promise<Blob | void> {
const headers = new Headers();
const bearer = `Bearer ${accessToken}`;
headers.append("Authorization", bearer);
headers.append("Content-Type", "image/jpg");
const options = {
method: "GET",
headers: headers
};
console.log("EXECUTING REQUEST");
return fetch("https://graph.microsoft.com/v1.0/me/photo/$value", options)
.then(response => response.blob())
.catch(error => console.log(error));
}
interface GraphMeResponse {
businessPhones: any[];
interface ProfileResponse {
displayName: string;
givenName: string;
jobTitle: string;
@@ -50,25 +30,14 @@ interface GraphMeResponse {
id: string;
}
export function useGraphProfile(): { graphData: GraphMeResponse; photo: string } {
const { instance, accounts } = useMsal();
const account = useAccount(accounts[0] || {});
const [graphData, setGraphData] = useState<GraphMeResponse>();
const [photo, setPhoto] = useState<string>();
export function useGraphProfile(): ProfileResponse {
const token = useAADToken();
const [profileResponse, setProfileResponse] = useState<ProfileResponse>();
useEffect(() => {
console.log("account", account);
if (account) {
instance
.acquireTokenSilent({
scopes: ["User.Read"],
account
})
.then(response => {
fetchMe(response.accessToken).then(response => setGraphData(response));
fetchPhoto(response.accessToken).then(response => setPhoto(URL.createObjectURL(response)));
});
if (token) {
fetchMe(token).then(response => setProfileResponse(response));
}
}, [account]);
return { graphData, photo };
}, [token]);
return profileResponse;
}

View File

@@ -11,7 +11,7 @@
"allowSyntheticDefaultImports": true,
"downlevelIteration": true,
"module": "esnext",
"target": "es5",
"target": "es2017",
"lib": ["es5", "es6", "dom", "webworker.importscripts"],
"jsx": "react",
"moduleResolution": "node",

View File

@@ -78,7 +78,7 @@ const ModulesRule = {
loader: "babel-loader",
options: {
cacheDirectory: ".cache/babel",
presets: [["@babel/preset-env", { targets: { ie: "11" }, useBuiltIns: false }]]
presets: [["@babel/preset-env", { targets: { chrome: "80" }, useBuiltIns: false }]]
}
}
],