我有一个身份服务器,一个JavaScript客户端和一个API . 所有这些都已配置,以便身份验证和授权按预期工作 . 我现在正试图通过我的API中的id(子声明)加载当前用户 . 问题是 User.Claims
枚举在我的所有控制器中都是空的 .
我已经解码了我在每次请求时发送的持有人令牌,并确认我有 sub
索赔 . 我的API是否需要一些额外的配置来接收这些声明?
解码JWT
{
"nbf": 1510436170,
"exp": 1510439770,
"iss": "https://localhost:44300",
"aud": [
"https://localhost:44300/resources",
"mycustom.api"
],
"client_id": "mycustom.web",
"sub": "c92cc2bc-d063-49d6-a36e-f6340796df15",
"auth_time": 1510435257,
"idp": "local",
"scope": [
"openid",
"profile",
"mycustom.api"
],
"amr": [
"pwd"
]
}
API配置
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<BrewSwapDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44300";
options.ApiName = "mycustom.api";
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder =>
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
客户端配置
在SPA客户端我使用 angular-auth-oidc-client
. 同样,我能够检查每个请求中的持有者令牌,并且可以看到我需要的 sub
声明 . 请参阅上面解码的JWT .
let oidcConfig = new OpenIDImplicitFlowConfiguration()
oidcConfig.stsServer = "https://localhost:44300";
oidcConfig.redirect_url = "https://localhost:44302";
oidcConfig.client_id = 'mycustom.web';
oidcConfig.response_type = 'id_token token';
oidcConfig.scope = 'openid profile mycustom.api';
oidcConfig.post_logout_redirect_uri = "https://localhost:44302";
oidcConfig.start_checksession = false;
oidcConfig.silent_renew = true;
oidcConfig.silent_renew_offset_in_seconds = 0;
oidcConfig.startup_route = '/home';
oidcConfig.auto_userinfo = true;
oidcConfig.log_console_warning_active = true;
oidcConfig.log_console_debug_active = true;
oidcConfig.max_id_token_iat_offset_allowed_in_seconds = 10;
oidcConfig.storage = localStorage;
API控制器
public class ExampleController : Controller
{
private readonly MyDbContext _context;
public ExampleController(MyDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<Example> GetExamples()
{
var test = User.Claims;
return _context.Examples;
}
}
你可以在下面看到发现了一个身份......
但它有0个索赔 .
1 回答
API Setup correction:
这是
ConfigureServices
方法的正确代码 .由于信息是由来自IdentityServer4的声明提供的,因此不需要AddIdentity .