【发布时间】:2018-12-05 16:04:24
【问题描述】:
这对我来说是全新的,我仍在努力解决它。我已经设置了 IDP(Identity Server 4),并且能够配置客户端对其进行身份验证(Angular 6 App),并进一步对 API 进行身份验证(Asp.Net Core 2.0)。一切似乎都很好。
这是 IDP 中的客户端定义:
new Client
{
ClientId = "ZooClient",
ClientName = "Zoo Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = true,
RedirectUris = { "http://localhost:4200/home" },
PostLogoutRedirectUris = { "http://localhost:4200/home" },
AllowedCorsOrigins = { "http://localhost:4200" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.Phone,
IdentityServerConstants.StandardScopes.Address,
"roles",
"ZooWebAPI"
}
}
我在客户端中请求以下范围: 'openid 个人资料电子邮件角色 ZooWebAPI'
WebAPI 是这样设置的:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvcCore()
.AddJsonFormatters()
.AddAuthorization();
services.AddCors();
services.AddDistributedMemoryCache();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44317";
options.RequireHttpsMetadata = false;
options.ApiName = "ZooWebAPI";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(policy =>
{
policy.WithOrigins("http://localhost:4200");
policy.AllowAnyHeader();
policy.AllowAnyMethod();
policy.AllowCredentials();
policy.WithExposedHeaders("WWW-Authenticate");
});
app.UseAuthentication();
app.UseMvc();
}
通过使用 [Authorize],我成功地保护了 API:
[Route("api/[controller]")]
[Authorize]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public ActionResult Get()
{
return new JsonResult(User.Claims.Select(
c => new { c.Type, c.Value }));
}
}
一切正常,如果客户端未通过身份验证,浏览器转到 IDP,需要身份验证,使用访问令牌重定向回来,然后将访问令牌用于成功进行的 API 调用。
如果我查看 User 对象中的 Claims,我可以看到一些信息,但我没有任何用户信息。我可以看到范围等,但例如没有角色。从我读到的内容来看,这是可以预料的,API 不应该关心用户在调用它,但是我将如何通过基于角色来限制 API 调用呢?还是会完全违反规范?
IDP 有一个返回所有用户信息的 userinfo 端点,我认为这将在 WebAPI 中使用,但再次,从一些阅读来看,它的意图是从仅限客户端。
无论如何,我想根据特定用户的角色来限制 Web API 调用。有没有人有什么建议,cmets?另外,我想知道是哪个用户拨打电话,我该怎么做?
JWT 示例:
谢谢
【问题讨论】:
标签: asp.net-web-api asp.net-core jwt identityserver4