Azure AD 和 Identity Server4 客户端身份验证和授权

使用 React 和 IdentityServer4 进行身份验证

1.安装所需的库

复制代码
npm install oidc-client

2.配置 IdentityServer4 客户端

在 IdentityServer4 中,需要配置一个客户端来使用 OpenID Connect 协议进行身份验证。客户端需要配置客户端 ID、客户端秘钥、重定向 URI 和要请求的 scope,如:

复制代码
new Client
{
    ClientId = "react-app",
    ClientName = "React Application",
    AllowedGrantTypes = GrantTypes.Code,
    RequireConsent = false,
    RedirectUris = { "http://localhost:3000/callback.html" },
    PostLogoutRedirectUris = { "http://localhost:3000/" },
    AllowedScopes = { "openid", "profile" },
    ClientSecrets = new List<Secret>
    {
        new Secret("your_client_secret".Sha256())
    },
    AllowAccessTokensViaBrowser = true
};

3.在 React 中配置 OpenID Connect 客户端

复制代码
import { UserManager } from 'oidc-client';

const userManager = new UserManager({
    authority: 'http://localhost:5000',
    client_id: 'react-app',
    redirect_uri: 'http://localhost:3000/callback.html',
    response_type: 'code',
    scope: 'openid profile',
    post_logout_redirect_uri: 'http://localhost:3000/',
    monitorInterval: 10000,
    checkSessionInterval: 2000,
    automaticSilentRenew: true,
    filterProtocolClaims: true,
    loadUserInfo: true
});

// 若要登录,请使用以下代码:
userManager.signinRedirect();

// 若要注销,请使用以下代码:
userManager.signoutRedirect();

authority 参数是 IdentityServer4 实例的 URL。client_id 参数是在 IdentityServer4 中配置的客户端 ID。redirect_uri 参数是在 IdentityServer4 中配置的回调 URL。response_type 参数是 code,表示使用授权码模式。scope 参数指定要请求的 scope。post_logout_redirect_uri 参数是注销后要重定向的 URL。monitorIntervalcheckSessionInterval 参数分别用于轮询客户端会话状态和检查用户会话状态。automaticSilentRenew 参数用于启用自动静默更新。filterProtocolClaims 参数表示使用令牌的协议声明,loadUserInfo 参数表示加载用户信息。

4.处理身份验证回调

定义了一个名为 Callback 的组件来处理身份验证回调

复制代码
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Callback from './Callback';

const App = () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/callback.html" component={Callback} />
                {/* 其他路由 */}
            </Switch>
        </BrowserRouter>
    );
};

export default App;

使用 React 和Azure AD 进行身份验证

使用 React 和 Azure AD 进行身份验证可以使用 OpenID Connect 和 Microsoft 身份验证库 for JavaScript (MSAL.js)来完成。
1.安装所需的库

复制代码
npm install msal

2.配置 Azure AD 应用程序

Azure AD 应用程序需要具有适当的设置,以接受来自 React 应用程序的请求。需要为 Azure AD 应用程序配置重定向 URI、获取的 scopes 和访问令牌等内容。例如:

复制代码
{
   "appId": "your_app_id_here",
   "appSecret": "your_secret_here",
   "redirectUri": "http://localhost:3000",
   "scopes": ["User.Read"],
   "authority": "https://login.microsoftonline.com/your_tenant_id_here"
}

2.在 React 中配置 MSAL.js

复制代码
import { PublicClientApplication } from "@azure/msal-browser";

const msalConfig = {
  auth: {
    clientId: "your_client_id_here",
    authority: "https://login.microsoftonline.com/your_tenant_id_here",
    redirectUri: "http://localhost:3000",
  },
  cache: {
    cacheLocation: "sessionStorage",
  },
};

const msalInstance = new PublicClientApplication(msalConfig);

export default msalInstance;

clientId 是 Azure AD 应用程序的 ID,authority 是 https://login.microsoftonline.com/ 加上Azure AD 租户 ID。redirectUri 是 React 应用程序的回调 URL。此外,将cacheLocation设置为"sessionStorage",这意味着令牌信息只会在浏览器窗口或浏览器标签关闭时才会失效。
4.处理身份验证回调

复制代码
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { MsalAuthenticationTemplate, useMsal } from "@azure/msal-react";
import { Loading } from "./components";
import { HomePage, ProfilePage } from './pages';

const ProtectedRoute = ({ children, ...rest }) => {
    const { instance, accounts, inProgress } = useMsal();
    const isAuthenticated = accounts.length > 0;
    if (inProgress === "loginRedirect" || inProgress === "acquireTokenRedirect") {
        return <Loading />;
    }

    return (
        <Route {...rest}>
            {isAuthenticated ? (
                children
            ) : (
                instance.loginRedirect({
                    scopes: ["openid", "profile"],
                })
            )}
        </Route>
    );
};

const App = () => {
    return (
        <BrowserRouter>
            <MsalAuthenticationTemplate>
                <Switch>
                       <Route exact path="/">
                           <HomePage />
                       </Route>
                       <ProtectedRoute exact path="/profile">
                           <ProfilePage />
                       </ProtectedRoute>
                </Switch>
            </MsalAuthenticationTemplate>
        </BrowserRouter>
    );
};

export default App;

使用 MsalAuthenticationTemplate 包装了我们的路由,以便我们可以利用 useMsal hook 来获取 instance,并通过 instance.loginRedirect() 方法登录用户。

相关推荐
Azure DevOps1 天前
Azure DevOps Server 正式版本发布
运维·microsoft·azure·devops
Channing Lewis4 天前
vault分生产和dev吗?也就是说是否支持在一个azure app中创建vault,但是分为生产和dev,而不是为生产和dev分别创建一个app
microsoft·azure
切糕师学AI6 天前
Azure RTOS ThreadX 简介
microsoft·嵌入式·azure·rtos
开开心心_Every13 天前
Word转PDF工具,免费生成图片型文档
网络·笔记·pdf·word·powerpoint·excel·azure
Leinwin14 天前
Azure NCv6 现已开放公共预览
microsoft·azure
具***715 天前
自动驾驶学习宝藏:Autoware Universe 中英对照技术文档
azure
询问QQ:6882388616 天前
线性与非线性MPC控制的四旋翼轨迹跟踪仿真对比研究
azure
宝桥南山19 天前
Azure - 尝试使用一下Kusto Query Language(KQL)
sql·microsoft·微软·database·azure·powerbi
安得权23 天前
Office365 SSO Azure的配置笔记
笔记·flask·azure
kaozhengpro25 天前
微軟 AZ-204 認證考試介紹|Developing Solutions for Microsoft Azure 完整指南
microsoft·azure