【发布时间】:2017-02-07 02:42:39
【问题描述】:
我正在实施 IdentityServer4 我正在制作 3 个不同的项目:
- IdentityServer (http://localhost:5000)
- API (http://localhost:5001)
- Javascript 客户端 (http://localhost:5003)
所有项目都是用 ASP.NET Core 创建的,但是 JS Client 使用的是静态文件。
我需要 JS 客户端仅使用身份令牌(而不是访问令牌)连接 API,因为我只需要访问 API,不需要管理用户身份验证。
我正在阅读快速入门帖子https://identityserver4.readthedocs.io/en/dev/quickstarts/1_client_credentials.html
当我阅读时,我认为我需要使用 Implicit Grand Type,我不需要 OpenID Connect,只需要 OAuth2。
我也读过这篇文章 https://identityserver4.readthedocs.io/en/dev/quickstarts/7_javascript_client.html 但是他们使用访问令牌,我不需要它,连接到 API 我正在使用 oidc-client-js 库 https://github.com/IdentityModel/oidc-client-js 并且我搜索使用隐式大类型的方式,但我使用的方法将我重定向到http://localhost:5000/connect/authorize页面(我想这是我需要使用OpenID Connect的时候)
实现这一目标的最佳方法是什么? 我有什么错? 如何使用 api 进行身份验证并调用 http://localhost:5001/values
IdentityServer 项目
Config.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"
}
}
};
}
Startup.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 项目
Startup.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>
【问题讨论】:
-
为什么不让 API 匿名并节省大量工作?您必须在 JavaScript 中对 Client ID + Client Secret 进行硬编码,这意味着它们已被泄露,无法在 JavaScript 中保密。
-
是的,我正在阅读更多,我需要的是 Implicit Grand Type aaronparecki.com/2012/07/29/2/oauth2-simplified 但我不知道如何正确使用它
-
IdentityServer4 有一个公共 api 类型,这是我正在尝试使用的。
-
我建议阅读richard-banks.org/2018/11/…,这是一个很好的开始,让所有人都觉得有效
标签: javascript c# oauth-2.0 asp.net-core-1.0 identityserver4