Adding Azure AD B2C to React Native App
Register your app in Azure active directory
1. Go to azure ad b2c, app registrations -> new registration
2. Enter some name, redirect uri => Single Page Application = http://localhost:3000
3. Open app just created, click Api
permission, assign permission Microsoft Graph- user.Read.All
4. Go to app Overview page, copy client
id and tenant id
Changes in React Js (Javascript language)
1. Create new app “npx create-react-app my-app”
2. Cd my-app
3. Install packages “npm install @azure/msal-browser @azure/msal-react”
4. Run npm install
5. Run npm start to run project
6. Changes in App.js
import logo from './logo.svg';
import './App.css';
import { useIsAuthenticated, useMsal } from "@azure/msal-react";
import { Login } from "./Login";
function App() {
const isAuthenticated = useIsAuthenticated();
const { instance, accounts } = useMsal();
return (
<div>
{isAuthenticated ? (
<div>
<h1>Welcome to our application. You are logged in</h1>
{accounts && accounts.length > 0 && (
<div>
<p>Username: {accounts[0].username}</p>
<p>User ID (Home Account ID): {accounts[0].homeAccountId}</p>
</div>
)}
</div>
) : (
<Login />
)}
</div>
);
}
export default App;
7. add a file in src folder ‘authConfig.js’
import { CLIENT_ID } from "./constants";
import { TENANT_ID } from "./constants";
export const msalConfig = {
auth: {
clientId: CLIENT_ID,
authority: `https://login.microsoftonline.com/${TENANT_ID}`,
redirectUri: "http://localhost:3000",
},
};
export const loginRequest = {
scopes: ["openid", "profile"],
};
8. Add constants.js in src folder
export const CLIENT_ID ="0daba125-36a6-44e7-a97a-bf4fe79aa57a";
export const TENANT_ID ="51962fd4-2ece-4606-bdbe-cc684c94f8b0"
9. Changes to make in index.js
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./authConfig";
const root = ReactDOM.createRoot(document.getElementById("root"));
const msalInstance = new PublicClientApplication(msalConfig);
root.render(
<MsalProvider instance={msalInstance}>
<App />
</MsalProvider>
);
10. add a login.js
import { useMsal } from "@azure/msal-react";
import { loginRequest } from "./authConfig";
export const Login = () => {
const { instance } = useMsal();
const handleLogin = () => {
instance.loginPopup(loginRequest).catch((e) => {
console.error(e);
});
};
return (
<div>
<button onClick={handleLogin}>Login With Azure AD</button>
</div>
);
};
Changes in React JS (TypeScript language)
Step 1: Create a new file (e.g., msalConfig.ts) to configure MSAL.
import { Configuration } from "@azure/msal-browser";
const clientAppId = "your_client_id";
const tenantId = "your_tenant_id";
const policyName = "your_policy_name";
const msalConfig: Configuration = {
auth: {
clientId: clientAppId,
authority: `https://${tenantId}.b2clogin.com/${tenantId}.onmicrosoft.com/${policyName}`,
knownAuthorities: [`https://${tenantId}.b2clogin.com/${tenantId}.onmicrosoft.com/${policyName}`],
},
};
export default msalConfig;
Step 2: Implement Authentication
- Create a new component (e.g., AuthProvider.tsx) to wrap your app with the MSAL authentication provider.
import { MsalProvider } from "@azure/msal-react";
import { PublicClientApplication } from "@azure/msal-browser";
import msalConfig from "./msalConfig";
const msalInstance = new PublicClientApplication(msalConfig);
const AuthProvider = ({ children }: { children: React.ReactNode }) => {
return <MsalProvider instance={msalInstance}>{children}</MsalProvider>;
};
export default AuthProvider;
Step 3: Use Authentication in Your App main.tsx
- Wrap your app with the AuthProvider component.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "bootstrap/dist/css/bootstrap.min.css";
import App from "./App.tsx";
import AuthProvider from "./components/admin/AuthProvider";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<AuthProvider>
<App />
</AuthProvider>
</StrictMode>
);
Step 4: Implement Login and Logout, login.tsx
- Use the useMsal hook to access the MSAL instance and implement login and logout functionality.
import { useMsal } from "@azure/msal-react";
import { useNavigate } from "react-router-dom";
const App = () => {
const { instance, accounts } = useMsal();
const handleLogin = () => {
instance.loginPopup().then((response) => {
const username = response.account.username;
const userid = response.account.localAccountId;
localStorage.setItem("token", userid);
localStorage.setItem("username", username);
navigate("/");
});
};
const handleLogout = () => {
instance.logoutPopup();
};
return (
<div>
{accounts.length > 0 ? (
<button onClick={handleLogout}>Logout</button>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
};
Step 5: App.tsx
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
import Layout from "./components/Layout";
import Home from "./components/Home";
import Login from "./components/admin/Login";
import Register from "./components/admin/Register";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const App = () => {
const { accounts } = useMsal();
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
if (!accounts.length) {
return <Navigate to="/login" />;
}
return <>{children}</>;
};
return (
<BrowserRouter>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route
path="/"
element={
<ProtectedRoute>
<Layout />
</ProtectedRoute>
}
>
<Route index element={<Home />} />
<Route path="home" element={<Home />} />
<Route path="changepassword" element={<ChangePassword />} />
</Route>
</Routes>
<ToastContainer />
</BrowserRouter>
);
};
export default App;
No comments:
Post a Comment