使用Bearer令牌访问IdentityServer4上受保护的API [英] Accessing protected API on IdentityServer4 with Bearer Token
问题描述
我试图寻找解决此问题的方法,但是没有找到正确的搜索文字.
I have attempted to search for a solution to this problem, but have not found the right search text.
我的问题是,如何配置我的IdentityServer,使其也可以使用BearerTokens接受/授权Api请求?
My question is, how can I configure my IdentityServer so that it will also accept/authorize Api Requests with BearerTokens?
我已配置并正在运行IdentityServer4. 我还在我的IdentityServer上配置了一个测试API,如下所示:
I have an IdentityServer4 configured and running. I also have configured a Test API on my IdentityServer like below:
[Authorize]
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
在我的startup.cs中,ConfigureServices()如下:
In my startup.cs ConfigureServices() is as follows:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
...
// configure identity server with stores, keys, clients and scopes
services.AddIdentityServer()
.AddCertificateFromStore(Configuration.GetSection("AuthorizationSettings"), loggerFactory.CreateLogger("Startup.ConfigureServices.AddCertificateFromStore"))
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.DefaultSchema = "auth";
options.ConfigureDbContext = builder =>
{
builder.UseSqlServer(databaseSettings.MsSqlConnString,
sql => sql.MigrationsAssembly(migrationsAssembly));
};
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.DefaultSchema = "auth";
options.ConfigureDbContext = builder =>
builder.UseSqlServer(databaseSettings.MsSqlConnString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
})
// this uses Asp Net Identity for user stores
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<AppProfileService>()
;
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = authSettings.AuthorityUrl;
options.RequireHttpsMetadata = authSettings.RequireHttpsMetadata;
options.ApiName = authSettings.ResourceName;
})
和Configure()如下:
and Configure() is as follows:
// NOTE: 'UseAuthentication' is not needed, since 'UseIdentityServer' adds the authentication middleware
// app.UseAuthentication();
app.UseIdentityServer();
我有一个配置为允许隐式授予类型的客户端,并且已将配置的 ApiName 包含为AllowedScopes之一:
I have a client configured to allow Implicit grant types and have included the configured ApiName as one of the AllowedScopes:
new Client
{
ClientId = "47DBAA4D-FADD-4FAD-AC76-B2267ECB7850",
ClientName = "MyTest.Web",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
RedirectUris = { "http://localhost:6200/assets/oidc-login-redirect.html", "http://localhost:6200/assets/silent-redirect.html" },
PostLogoutRedirectUris = { "http://localhost:6200/?postLogout=true" },
AllowedCorsOrigins = { "http://localhost:6200" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"dev.api",
"dev.auth" // <- ApiName for IdentityServer authorization
},
AllowAccessTokensViaBrowser = true,
AllowOfflineAccess = true,
AccessTokenLifetime = 18000,
},
当我使用Postman访问受保护的API时,即使将有效的Bearer Token添加到了Request标头中,它总是重定向到Login页面.
When I use Postman to access the protected API but it always redirects to the Login page even though a valid Bearer Token has been added to the Request header.
注释[Authorize]属性将正确返回响应,但是User.Claims当然为空.
Commenting out the [Authorize] attribute will correctly return a response, but of course the User.Claims are empty.
(通过浏览器)登录IdentityServer,然后(通过浏览器)访问API时,它还将返回响应.这次,User.Claims可用了.
When logging into the IdentityServer (via a browser) and then accessing the API (via the browser) it will also return a response. This time, the User.Claims are available.
推荐答案
下面是一个在IdentityServer内部共同托管受保护API的示例:
There is an example co-hosting a protected API inside IdentityServer: IdentityServerAndApi
我与他们的启动公司之间的快速比较是,他们正在调用AddJwtBearer
而不是AddIdentityServerAuthentication
:
I quick comparison between their startup and yours is that they are calling AddJwtBearer
instead of AddIdentityServerAuthentication
:
services.AddAuthentication()
.AddJwtBearer(jwt => {
jwt.Authority = "http://localhost:5000";
jwt.RequireHttpsMetadata = false;
jwt.Audience = "api1";
});
Authorize
属性还设置身份验证方案:
TheAuthorize
attribute also sets the authentication scheme:
[Authorize(AuthenticationSchemes = "Bearer")]
这篇关于使用Bearer令牌访问IdentityServer4上受保护的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!