gpt4 book ai didi

javascript - 如何在 ClientCredentials ASP.NET Core 中使用 IdentityServer4 和 Javascript 客户端

转载 作者:可可西里 更新时间:2023-11-01 02:47:20 24 4
gpt4 key购买 nike

我正在实现 IdentityServer4,我正在制作 3 个不同的项目:

所有项目均使用 ASP.NET Core 创建,但 JS 客户端使用静态文件。

我需要 JS 客户端仅使用身份 token (而非访问 token )与 API 连接,因为我只需要访问 API,不需要管理用户身份验证。

我正在阅读快速入门帖子 https://identityserver4.readthedocs.io/en/dev/quickstarts/1_client_credentials.html

当我阅读时,我认为我需要使用隐式大类型,我不需要 OpenID Connect,只需要 OAuth2。

我也看了这篇文章 https://identityserver4.readthedocs.io/en/dev/quickstarts/7_javascript_client.html但他们使用访问 token ,我不需要它,连接到我正在使用 oidc-client-js 库的 API https://github.com/IdentityModel/oidc-client-js我搜索使用隐式大类型的方法,但我使用的方法将我重定向到 http://localhost:5000/connect/authorize页面(我认为这是我需要使用 OpenID Connect 的时候)

实现该目标的最佳方法是什么?我有什么问题吗?我如何使用 api 进行身份验证并调用 http://localhost:5001/values

IdentityServer 项目

配置.cs

public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
ClientName = "JavaScript Client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,



RedirectUris = new List<string>
{
"http://localhost:5003/oidc-client-sample-callback.html"
},
AllowedCorsOrigins = new List<string>
{
"http://localhost:5003"
},

// scopes that client has access to
AllowedScopes = new List<string>
{
"api1"
}
}
};
}

启动.cs

    public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and scopes
services.AddDeveloperIdentityServer()
.AddInMemoryScopes(Config.GetScopes())
.AddInMemoryClients(Config.GetClients());
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Debug);
app.UseDeveloperExceptionPage();

app.UseIdentityServer();
}

API 项目

启动.cs

public void ConfigureServices(IServiceCollection services)
{

// Add framework services.
services.AddMvc();

services.AddSingleton<ITodoRepository, TodoRepository>();

services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:5003")
.AllowAnyHeader()
.AllowAnyMethod();
});
});

services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();


}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseCors("default");

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5000",
ScopeName = "api1",

RequireHttpsMetadata = false
});

app.UseMvc();

}

ValuesController.cs

[Route("api/[controller]")]
[Authorize]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value3" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
}

Javascript 客户端项目

oidc-client-sample.html

<!DOCTYPE html>
<html>
<head>
<title>oidc-client test</title>
<link rel='stylesheet' href='app.css'>
</head>
<body>
<div>
<a href='/'>home</a>
<a href='oidc-client-sample.html'>clear url</a>
<label>
follow links
<input type="checkbox" id='links'>
</label>
<button id='signin'>signin</button>
<button id='processSignin'>process signin response</button>
<button id='signinDifferentCallback'>signin using different callback page</button>
<button id='signout'>signout</button>
<button id='processSignout'>process signout response</button>
</div>

<pre id='out'></pre>

<script src='oidc-client.js'></script>
<script src='log.js'></script>
<script src='oidc-client-sample.js'></script>
</body>
</html>

oidc-client-sample.js

///////////////////////////////
// UI event handlers
///////////////////////////////
document.getElementById('signin').addEventListener("click", signin, false);
document.getElementById('processSignin').addEventListener("click", processSigninResponse, false);
document.getElementById('signinDifferentCallback').addEventListener("click", signinDifferentCallback, false);
document.getElementById('signout').addEventListener("click", signout, false);
document.getElementById('processSignout').addEventListener("click", processSignoutResponse, false);
document.getElementById('links').addEventListener('change', toggleLinks, false);

///////////////////////////////
// OidcClient config
///////////////////////////////
Oidc.Log.logger = console;
Oidc.Log.level = Oidc.Log.INFO;

var settings = {
authority: 'http://localhost:5000/',
client_id: 'client',
redirect_uri: 'http://localhost:5003/oidc-client-sample-callback.html',
response_type: 'token',
scope: 'api1'
};
var client = new Oidc.OidcClient(settings);

///////////////////////////////
// functions for UI elements
///////////////////////////////
function signin() {
client.createSigninRequest({ data: { bar: 15 } }).then(function (req) {
log("signin request", req, "<a href='" + req.url + "'>go signin</a>");
if (followLinks()) {
window.location = req.url;
}
}).catch(function (err) {
log(err);
});
}
function api() {
client.getUser().then(function (user) {
var url = "http://localhost:5001/values";

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();
});
}

oidc-client-sample-callback.html

<!DOCTYPE html>
<html>
<head>
<title>oidc-client test</title>
<link rel='stylesheet' href='app.css'>
</head>
<body>
<div>
<a href="oidc-client-sample.html">back to sample</a>
</div>
<pre id='out'></pre>
<script src='log.js'></script>
<script src='oidc-client.js'></script>
<script>
Oidc.Log.logger = console;
Oidc.Log.logLevel = Oidc.Log.INFO;
new Oidc.OidcClient().processSigninResponse().then(function(response) {
log("signin response success", response);
}).catch(function(err) {
log(err);
});
</script>
</body>
</html>

最佳答案

据我所知,您的代码应该可以工作,它可以完成所有工作。

  1. 您的 JavaScript 应用程序 (localhost:5003) 请求一个 token (function signin())。这将导致重定向到 IdentityServer
  2. IdentityServer (localhost:5000) 已设置,客户端设置 (Client.cs) 与请求匹配。尽管缺少用户和资源的配置:请参阅此处:https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/3_ImplicitFlowAuthentication/src/QuickstartIdentityServer/Startup.cs
  3. 您的 JavaScript 应用程序有一个正确的“着陆页”,即成功登录后 IdentityServer 重定向回的页面。此页面获取新颁发的 token (new Oidc.OidcClient().processSigninResponse())
  4. 您的 JavaScript 应用随其 API 请求发送 token (xhr.setRequestHeader("Authorization", "Bearer "+ user.access_token);)
  5. 您的 API (localhost:5001) 已正确设置并将针对您的 IdentityServer 进行授权

所以我认为代码是正确的,但对术语有一些误解。

  • 您需要隐式授权。忘掉 ClientCredentials,因为它是为另一个工作流设计的,不应该在浏览器中使用,因为客户端 secret 被暴露了。这意味着任何人都可以发出有效 token (“窃取”)并且您的安全性受到威胁。 (如果您必须使用 ClientCredentials,请创建服务器代理方法)。
  • 您需要 OpenID Connect (OIDC) 和 OAuth2。 (这些定义不准确!!)OIDC 为您颁发 token (“让用户登录”),而 OAuth2 验证 token 。别担心,IdentityServer 会搞定这一切。
  • 您需要访问 token 。为请求者(您的 localhost:5003 JavaScript 应用程序)颁发身份 token ,访问 token 应“转发”到 API(您的 localhost:5001 API)
  • “登录”的重定向是正常的。这是 Web 应用程序的典型工作流程:您离开应用程序 (localhost:5003) 并最终进入 IdentityServer (http://localhost:5000)。成功登录后,您将被重定向回您的应用程序 (localhost:5003)

关于javascript - 如何在 ClientCredentials ASP.NET Core 中使用 IdentityServer4 和 Javascript 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39759010/

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