gpt4 book ai didi

reactjs - 在 React 前端中使用 oidc-client.js 和 Identityserver4 进行身份验证

转载 作者:行者123 更新时间:2023-12-03 13:14:52 26 4
gpt4 key购买 nike

最近我尝试使用 IdentityServer4 和 React 客户端来设置身份验证。我按照 IdentityServer 文档的添加 JavaScript 客户端教程(部分)进行操作:https://media.readthedocs.org/pdf/identityserver4/release/identityserver4.pdf还使用 Quickstart7_JavaScriptClient 文件。

缺点是我使用 React 作为前端,而我对 React 的了解不足以使用 React 实现教程中使用的相同功能。

尽管如此,我还是开始阅读并尝试开始使用它。我的 IdentityServer 项目和 API 已设置并且似乎工作正常(也与其他客户端进行了测试)。

我首先将 oidc-client.js 添加到我的 Visual Code 项目中。接下来,我创建了一个在开始时呈现的页面(将其命名为 Authentication.js),这是包含登录、调用 API 和注销按钮的地方。此页面(Authentication.js)如下所示:

import React, { Component } from 'react';
import {login, logout, api, log} from '../../testoidc'
import {Route, Link} from 'react-router';

export default class Authentication extends Component {
constructor(props) {
super(props);
}

render() {
return (
<div>
<div>
<button id="login" onClick={() => {login()}}>Login</button>
<button id="api" onClick={() => {api()}}>Call API</button>
<button id="logout" onClick={() => {logout()}}>Logout</button>

<pre id="results"></pre>

</div>

<div>
<Route exact path="/callback" render={() => {window.location.href="callback.html"}} />

{/* {<Route path='/callback' component={callback}>callback</Route>} */}
</div>
</div>
);
}
}

在 testoidc.js 文件(上面导入的)中,我添加了所有使用的 oidc 函数(示例项目中的 app.js)。路由部分应该使callback.html可用,我已按原样保留该文件(这可能是错误的)。

testoidc.js 文件包含以下功能:

import Oidc from 'oidc-client'


export function log() {
document.getElementById('results').innerText = '';

Array.prototype.forEach.call(arguments, function (msg) {
if (msg instanceof Error) {
msg = "Error: " + msg.message;
}
else if (typeof msg !== 'string') {
msg = JSON.stringify(msg, null, 2);
}
document.getElementById('results').innerHTML += msg + '\r\n';
});
}

var config = {
authority: "http://localhost:5000",
client_id: "js",
redirect_uri: "http://localhost:3000/callback.html",
response_type: "id_token token",
scope:"openid profile api1",
post_logout_redirect_uri : "http://localhost:3000/index.html",
};
var mgr = new Oidc.UserManager(config);

mgr.getUser().then(function (user) {
if (user) {
log("User logged in", user.profile);
}
else {
log("User not logged in");
}
});

export function login() {
mgr.signinRedirect();
}

export function api() {
mgr.getUser().then(function (user) {
var url = "http://localhost:5001/identity";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
});
}

export function logout() {
mgr.signoutRedirect();
}

有很多地方出了问题。当我单击登录按钮时,我被重定向到 IdentityServer 的登录页面(这很好)。当我使用有效凭据登录时,我将被重定向到我的 React 应用程序:http://localhost:3000/callback.html#id_token=Token

Identity项目中的这个客户端定义如下:

new Client
{
ClientId = "js",
ClientName = "JavaScript Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,

// where to redirect to after login
RedirectUris = { "http://localhost:3000/callback.html" },

// where to redirect to after logout
PostLogoutRedirectUris = { "http://localhost:3000/index.html" },

AllowedCorsOrigins = { "http://localhost:3000" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}

}

不过,回调函数似乎从未被调用,它只是停留在回调 URL 上,后面有一个很长的标记..

此外,登录后 getUser 函数一直显示“用户未登录”,并且“调用 API”按钮一直显示没有 token 。很明显事情没有正常工作。我只是不知道哪里出了问题。检查时,我可以看到本地存储中生成了一个 token :

enter image description here

此外,当我单击注销按钮时,我会被重定向到身份主机的注销页面,但是当我单击那里的注销时,我不会被重定向到我的客户端。

我的问题是:

  • 我是否走在与 IdentityServer4 结合实现 oidc-client 的正确轨道上?
  • 我是否使用了正确的库,或者 React 是否需要与 oidc-client.js 不同的库。
  • 是否有任何教程将 React 前端与 IdentityServer4 和 oidc-client (不带 redux)结合使用,我找不到。
  • 如何/在哪里添加callback.html,是否应该重写?

有人能指出我正确的方向吗,这里很可能有更多的事情出了问题,但目前我只是陷入了从哪里开始。

最佳答案

IdentityServer4只是OIDC的后端实现;因此,您所需要做的就是使用给定的 API 在客户端中实现流程。我不知道 oidc-client.js 文件是什么,但它很可能做与您自己实现相同的事情。流程本身非常简单:

  1. React 应用准备请求并使用 client_idredirect_uri(以及状态、随机数)将用户重定向到身份验证服务器
  2. IdentityServer 检查 client_idredirect_uri 是否匹配。
    • 如果用户未登录,则显示登录框
    • 如果需要同意书(类似于您在某些应用中通过 Facebook/Google 登录时),请显示必要的互动
    • 如果用户已通过身份验证和授权,则使用新参数将页面重定向到 redirect_uri。在您的情况下,URL 将如下所示:https://example.com/cb#access_token=...&id_token=...&stuff-like-nonce-and-state<
  3. 现在,React 应用需要解析 URL、访问值并将 token 存储在某个位置以供将来的请求使用:

实现逻辑的最简单方法是首先在路由器中设置一条路由,该路由解析为执行逻辑的组件。该组件可以是“不可见的”。它甚至不需要渲染任何东西。您可以这样设置路线:

<Route path="/cb" component={AuthorizeCallback} />

然后,在 AuthorizeCallback 组件中实现 OIDC 客户端逻辑。在组件中,你只需要解析URL即可。您可以使用location.hash访问 URL 的 #access_token=...&id_token=...&stuff-like-nonce-and-state 部分。您可以使用URLSearchParams或像 qs 这样的第三方库。然后,只需将值存储在某个地方(sessionStorage、localStorage,如果可能的话,还有 cookies)。您所做的任何其他事情都只是实现细节。例如,在我的一个应用程序中,为了记住用户在应用程序中所在的事件页面,我将该值存储在 sessionStorage 中,然后在 AuthorizeCallback 中使用该存储中的值来重定向用户到正确的页面。因此,Auth 服务器重定向到“/cb”,解析为 AuthorizeCallback,并且该组件根据用户所在位置重定向到所需位置(如果未设置位置,则重定向到“/”)。

此外,请记住,如果授权服务器的 session cookie 未过期,则在 token 过期或删除时您将不需要重新登录。如果 token 已过期,这很有用,但在您注销时可能会出现问题。这就是为什么当您注销时,您需要立即向授权服务器发送请求以删除/使 token 过期,然后再从存储中删除 token 。

关于reactjs - 在 React 前端中使用 oidc-client.js 和 Identityserver4 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49754595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com