Skip to content
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

DKM - Implement Authentication #19

Open
wants to merge 7 commits into
base: PSL-DEV
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 1 addition & 2 deletions App/backend-api/Microsoft.GS.DPS.Host/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Expand Down
43 changes: 26 additions & 17 deletions App/frontend-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import { SnackbarProvider } from "notistack";
import { SnackbarSuccess } from "./components/snackbar/snackbarSuccess";
import { SnackbarError } from "./components/snackbar/snackbarError";


import { MsalProvider } from '@azure/msal-react';
import { msalInstance } from './providers/msalInstance';
import AuthWrapper from './providers/AuthWrapper';

/* Application insights initialization */
//const reactPlugin: ReactPlugin = Telemetry.initAppInsights(window.ENV.APP_INSIGHTS_CS, true);

Expand All @@ -24,23 +29,27 @@ webLightTheme.colorNeutralForeground1 = (fullConfig.theme!.colors as any).black;

function App() {
return (
<Suspense>
{/* Removed MsalProvider and MsalAuthenticationTemplate */}
{/* <AppInsightsContext.Provider value={reactPlugin}> */}
<FluentProvider theme={webLightTheme}>
<BrowserRouter>
<SnackbarProvider
anchorOrigin={{ vertical: "top", horizontal: "center" }}
Components={{ success: SnackbarSuccess, error: SnackbarError }}
>
<Layout>
<AppRoutes />
</Layout>
</SnackbarProvider>
</BrowserRouter>
</FluentProvider>
{/* </AppInsightsContext.Provider> */}
</Suspense>
<MsalProvider instance={msalInstance}>
<AuthWrapper>
<Suspense>
{/* Removed MsalProvider and MsalAuthenticationTemplate */}
{/* <AppInsightsContext.Provider value={reactPlugin}> */}
<FluentProvider theme={webLightTheme}>
<BrowserRouter>
<SnackbarProvider
anchorOrigin={{ vertical: "top", horizontal: "center" }}
Components={{ success: SnackbarSuccess, error: SnackbarError }}
>
<Layout>
<AppRoutes />
</Layout>
</SnackbarProvider>
</BrowserRouter>
</FluentProvider>
{/* </AppInsightsContext.Provider> */}
</Suspense>
</AuthWrapper>
</MsalProvider>
);
}

Expand Down
83 changes: 55 additions & 28 deletions App/frontend-app/src/components/headerBar/headerBar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import React, { MouseEventHandler, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
import { Auth } from "../../utils/auth/auth";
//import { useMsal } from "@azure/msal-react";
//import { Auth } from "../../utils/auth/auth";

//import { loginRequest } from "../../msaConfig";
import { RedirectRequest } from "@azure/msal-browser";
import {
Avatar,
Expand All @@ -18,6 +20,12 @@ import resolveConfig from "tailwindcss/resolveConfig";
import TailwindConfig from "../../../tailwind.config";
import { isPlatformAdmin } from "../../utils/auth/roles";


import { useMsal, useIsAuthenticated } from "@azure/msal-react";
import { msalInstance } from "../../providers/msalInstance";
import { loginRequest } from "../../msaConfig";
import { AccountInfo } from "@azure/msal-browser";

const fullConfig = resolveConfig(TailwindConfig);
const useStylesAvatar = makeStyles({
root: {
Expand Down Expand Up @@ -51,14 +59,18 @@ interface NavItem {
export function HeaderBar({ location }: { location?: NavLocation }) {
const { t } = useTranslation();
const [openDrawer, setOpenDrawer] = useState(false);
const { instance, accounts } = useMsal();
//const { instance, accounts } = useMsal();
const navigate = useNavigate();
const stylesAvatar = useStylesAvatar();

const linkClasses = "cursor-pointer hover:no-underline hover:border-b-[3px] h-9 min-h-0 block text-white";
const linkCurrent = "pointer-events-none border-b-[3px]";
const isAuthenticated = accounts.length > 0;
const isAdmin = isPlatformAdmin(accounts);
//const isAuthenticated = accounts.length > 0;
//const isAdmin = isPlatformAdmin(accounts);

const { accounts, instance } = useMsal();
const isAuthenticated = useIsAuthenticated();
const activeAccount: AccountInfo | undefined = accounts[0];

const navItems: (NavItem | null)[] = useMemo(
() => [
Expand All @@ -79,21 +91,21 @@ export function HeaderBar({ location }: { location?: NavLocation }) {
// : null,
isAuthenticated
? {
key: "sign-out",
label: t("components.header-bar.sign-out"),
isPrimary: false,
action: signOut,
}
: null,
isAuthenticated
? {
key: "personalDocuments",
label: "Personal Documents",
isPrimary: false,
location: NavLocation.PersonalDocs,
to: "/personalDocuments",
}
key: "sign-out",
label: t("components.header-bar.sign-out"),
isPrimary: false,
action: signOut,
}
: null,
// isAuthenticated
// ? {
// key: "personalDocuments",
// label: "Personal Documents",
// isPrimary: false,
// location: NavLocation.PersonalDocs,
// to: "/personalDocuments",
// }
// : null,
],
[accounts]
);
Expand All @@ -102,13 +114,28 @@ export function HeaderBar({ location }: { location?: NavLocation }) {
setOpenDrawer((openDrawer) => !openDrawer);
}

function signIn() {
instance.loginRedirect(Auth.getAuthenticationRequest() as RedirectRequest);
}
// function signIn() {
// instance.loginRedirect(Auth.getAuthenticationRequest() as RedirectRequest);
// }

function signOut() {
instance.logoutRedirect();
}
// function signOut() {
// instance.logoutRedirect();
// }

async function signOut() {
if (activeAccount) {
try {
await instance.logoutRedirect({
account: activeAccount,
onRedirectNavigate: () => false, // Prevent default navigation
});
} catch (error) {
console.error("Logout failed:", error);
}
} else {
console.warn("No active account found for logout.");
}
};

function renderLink(nav: NavItem, className?: string) {
return (
Expand Down Expand Up @@ -138,17 +165,17 @@ export function HeaderBar({ location }: { location?: NavLocation }) {
<>
<div className="flex mr-20 ml-20 justify-between">
<div className="flex justify-between gap-3">
<img className="my-auto" src="/img/Contoso_Logo_sm.png" alt="logo" />
<img className="my-auto" src="/img/Contoso_Logo_sm.png" alt="logo" />
<div className="my-auto pb-3 text-lg font-semibold leading-tight text-white mt-3">
{t("components.header-bar.title")}
</div>
<div className="border border-zinc-500"></div>

<div className="order-5 my-auto pb-3 text-lg font-semibold leading-tight text-white mt-3">
{t("components.header-bar.sub-title")}
</div>
</div>

<nav className="whitespace-nowrap text-lg font-semibold leading-10">
<ul
className={
Expand Down
20 changes: 10 additions & 10 deletions App/frontend-app/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ import "./index.scss";
import { AppContextProvider } from "./AppContext";

declare global {
interface Window {
ENV: any; // eslint-disable-line @typescript-eslint/no-explicit-any
WcpConsent: any; // eslint-disable-line @typescript-eslint/no-explicit-any
}
interface Window {
ENV: any; // eslint-disable-line @typescript-eslint/no-explicit-any
WcpConsent: any; // eslint-disable-line @typescript-eslint/no-explicit-any

}
}

initializeLanguage();
initializeFileTypeIcons();

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
// <React.StrictMode>
<AppContextProvider>
<App />
</AppContextProvider>
// </React.StrictMode>
// <React.StrictMode>
<AppContextProvider>
<App />
</AppContextProvider>
// </React.StrictMode>
);
33 changes: 33 additions & 0 deletions App/frontend-app/src/msaConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// msalConfig.ts
import { Configuration, LogLevel } from '@azure/msal-browser';

export const msalConfig: Configuration = {
auth: {
clientId: import.meta.env.VITE_MSAL_AUTH_CLIENTID,
authority: import.meta.env.VITE_MSAL_AUTH_AUTHORITY,
redirectUri: import.meta.env.VITE_MSAL_REDIRECT_URL,
},
cache: {
cacheLocation: 'localStorage', // Use localStorage for persistent cache
storeAuthStateInCookie: false,
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) return;
if (level === LogLevel.Error) console.error(message);
if (level === LogLevel.Info) console.info(message);
if (level === LogLevel.Verbose) console.debug(message);
if (level === LogLevel.Warning) console.warn(message);
},
},
},
};

export const loginRequest = {
scopes: ['User.Read'],
};

export const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
};
35 changes: 35 additions & 0 deletions App/frontend-app/src/providers/AuthWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

import React, { useEffect } from "react";
import { msalInstance } from "./msalInstance";
import { loginRequest } from "../msaConfig";
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
import { InteractionStatus } from "@azure/msal-browser";

const AuthWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { inProgress } = useMsal();
const isAuthenticated = useIsAuthenticated();

// Check for existing session and trigger login if not authenticated
const checkAuthentication = async () => {
const accounts = msalInstance.getAllAccounts();
if (accounts.length === 0 && inProgress === InteractionStatus.None) {
try {
await msalInstance.loginRedirect(loginRequest);
} catch (error) {
console.error("Login failed:", error);
}
}
};

useEffect(() => {
// Trigger login only if no interaction is in progress
if (!isAuthenticated && inProgress === InteractionStatus.None) {
checkAuthentication();
}
}, [isAuthenticated, inProgress]);

return <>{children}</>;
};

export default AuthWrapper;

5 changes: 5 additions & 0 deletions App/frontend-app/src/providers/msalInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// src/msalInstance.ts
import { PublicClientApplication } from "@azure/msal-browser";
import { msalConfig } from "../msaConfig";

export const msalInstance = new PublicClientApplication(msalConfig);
7 changes: 7 additions & 0 deletions Deployment/appconfig/frontapp/.env.template
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
VITE_API_ENDPOINT={{ backend-fqdn }}

VITE_MSAL_AUTH_CLIENTID={{ clientId }}

VITE_MSAL_AUTH_AUTHORITY={{ authority }}

VITE_MSAL_REDIRECT_URL={{ redirectUri }}

DISABLE_AUTH=true
Loading