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

相关推荐
营赢盈英2 天前
Give azure openai an encyclopedia of information
ai·openai·azure
全云在线allcloudonline2 天前
微软 Azure AI 服务免费试用及申请:语音识别、文本转语音、基于视觉、语言处理、文档分析等10大场景
人工智能·microsoft·azure
营赢盈英2 天前
Azure OpenAI and token limit
ai·chatgpt·asp.net·azure·openai api
营赢盈英2 天前
TypeError: expected string or buffer - Langchain, OpenAI Embeddings
langchain·azure·embeddings·openai api·rag
营赢盈英3 天前
Allow anonymous access to my Azure OpenAI chat bot
ai·openai·azure·webapps
AI人工智能集结号7 天前
使用您自己的图像微调 FLUX.1 LORA 并使用 Azure 机器学习进行部署
机器学习·flask·azure
AI人工智能集结号7 天前
使用 Azure 机器学习微调小型语言模型 (SLM) Phi-3
机器学习·语言模型·azure
NineData8 天前
K1计划100%收购 MariaDB; TDSQL成为腾讯云核心战略产品; Oracle@AWS/Google/Azure发布
数据库·oracle·腾讯云·mariadb·azure·amazon·tdsql
SteveMiller9 天前
使用Azure+C#+visual studio开发图像目标检测系统
c#·azure·visual studio
晨曦_子画9 天前
跨平台集成:在 AI、微服务和 Azure 云之间实现无缝工作流
人工智能·微服务·azure