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() 方法登录用户。

相关推荐
宝桥南山4 天前
Azure - 检查一下是否需要在Microsoft Extra ID中配置Passkeys认证方法
microsoft·微软·sass·azure
mit6.8245 天前
AKS--Azure Managed Kubernetes
kubernetes·flask·azure
编码者卢布11 天前
【Azure APIM】通过 API Management 公开API为 MCP Server 的试验 (二)
microsoft·flask·azure
编码者卢布12 天前
【Azure APIM】通过 API Management 公开现有 MCP Server 的试验 (一)
microsoft·flask·azure
立心者014 天前
Sdcb Chats .. 发布,彻底移除 Azure.AI.OpenAI 专用包
人工智能·flask·azure
韭菜炒鸡肝天15 天前
【App Service】在Azure环境中如何查看App Service实例当前的网络连接情况呢?
microsoft·flask·azure
国际云,接待19 天前
Azure Front Door WAF实战:托管规则、限速与日志查询
microsoft·网络安全·云计算·azure·front door
编码者卢布24 天前
【Azure Policy】Policy修正任务为Azure资源添加诊断日志报错问题的调查
microsoft·flask·azure
编码者卢布1 个月前
【Azure APIM】APIM的诊断日志与Application Insights的日志是否可以串联为一个端到端的日志链路呢?
python·flask·azure
MicrosoftReactor1 个月前
技术速递|基于 OpenClaw、MCP 和 Azure Container Apps 构建自主 Microsoft Teams 智能体
microsoft·agent·azure·teams·mcp