我有一个简单的 WebApi 项目,它使用IdentityServer4.AccessTokenValidation
验证由IdentityServer4
开发地址服务器:https://localhost:44347
我通过将以下数据发送到身份服务器来获取令牌:
POST
https://localhost:44347/connect/token
client_id:x.api.client
client_secret:secret
response_type:code id_token
scope:X.api
grant_type:client_credentials
回应是:
{
"access_token": "THETOKEN",
"expires_in": 1209600,
"token_type": "Bearer"
}
并将令牌发送到 WebAPI
POST
http://localhost:59062/identity
Authorization:Bearer THETOKEN
我得到了想要的结果,但是,添加以下代码的注释部分会导致 404 Not Found。
代码是:
public class Startup {
private const string API_NAME = "X.api";
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddLogging(configure => configure.AddConsole());
services.AddDbContext<MyDataContext>(options => options.UseSqlServer(connectionString));
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddTransient<IUserStore<MyUser>, MyUserStore>();
services.AddTransient<IRoleStore<MyRole>, RoleStore>();
services.AddTransient<IPasswordHasher<MyUser>, MyHasher>();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options => {
options.Authority = "https://localhost:44347";
options.RequireHttpsMetadata = false;
options.ApiName = API_NAME;
});
////This commented part brokes API
//services.AddIdentity<MyUser, MyRole>(options => {
// options.Password.RequireDigit = true;
// options.Password.RequiredLength = 6;
// options.Password.RequireNonAlphanumeric = false;
// options.Password.RequireUppercase = false;
// options.Password.RequireLowercase = false;
// options.SignIn.RequireConfirmedEmail = false;
//})
//Bekaz we are not using IdentityUser as base
//.AddUserStore<MyUserStore>()
//.AddRoleStore<RoleStore>()
//.AddDefaultTokenProviders();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
API 就像下面的代码一样简单(身份服务器的示例之一)
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace Api.Controllers {
[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase {
[HttpGet]
public IActionResult Get() {
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
我使用继承自的自定义 User 类IIdentity
, 风俗Role
and UserRole
, 风俗RoleStore
实施的IRoleStore<MyRole>
,和定制UserStore
实施的IUserStore<MyUser>, IUserPasswordStore<MyUser>
.
编辑,更多信息
这是我在控制台上得到的:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/identity
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Route matched with {action = "Get", controller = "Identity"}. Executing action Api.Controllers.IdentityController.Get ()
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
[16:48:20 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler
AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action Api.Controllers.IdentityController.Get () in 30.1049ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 103.2969ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Account/Login?ReturnUrl=%2Fidentity
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.468ms 404
临时解决方案
有东西与authorization system
,我终于将属性更改为我的在这里成立 https://stackoverflow.com/a/48890659/790896
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
它有效。但如何以及为什么?我现在还没有。
另外,改变AddAuthentication
正如上述答案所暗示的,下面的部分Does Not有效并需要(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)
传递给[Authorize]
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options => {
options.Authority = "https://localhost:44347";
options.RequireHttpsMetadata = false;
options.ApiName = API_NAME;
});
改变顺序,终于可以工作了。(首先AddIdentity
进而AddAuthentication
)
services.AddIdentity<MyUser, MyRole>(options => {
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.SignIn.RequireConfirmedEmail = false;
})
.AddUserStore<MyUserStore>()
.AddRoleStore<RoleStore>();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options => {
options.Authority = "https://localhost:44347";
options.RequireHttpsMetadata = false;
options.ApiName = API_NAME;
});