我在这里遵循OpenIddict示例中的确切示例:https://github.com/openiddict/openiddict-core。在我使用AddIdentity部分之前,一切都正常工作。我真的需要使用身份。注释掉Identity部分会起作用,如果它是未注释的,那么我在测试控制器中的get方法上会得到一个404,因为它不会授权。我使用的是.Net Core2.x
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<XXIdentityContext>(options =>
{
options.UseSqlServer(config["default:connectionString"]);
options.UseOpenIddict();
});
services.AddIdentity<AspUser, IdentityRole>()
.AddEntityFrameworkStores<XXIdentityContext>()
.AddDefaultTokenProviders();
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<XXIdentityContext>();
})
.AddServer(options =>
{
options.UseMvc();
options.EnableTokenEndpoint("/connect/token");
options.AllowPasswordFlow();
options.DisableHttpsRequirement();
options.AcceptAnonymousClients();
})
.AddValidation();
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseMvc();
}AspUser.cs:
public class AspUser : IdentityUser
{
}XXIdentityContext.cs:
public class XXIdentityContext: IdentityDbContext<AspUser>
{
private IConfiguration config;
public XXIdentityContext(DbContextOptions<XXIdentityContext> options, IConfiguration config) : base(options)
{
this.config = config;
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}TestController.cs:
public class TestController : Controller
{
[HttpPost("~/connect/token"), Produces("application/json")]
public IActionResult Exchange(OpenIdConnectRequest request)
{
var claims = new List<Claim>
{
new Claim(ClaimsConstants.Id, "bob"),
new Claim(ClaimsConstants.Temp, 5.ToString()),
new Claim(OpenIdConnectConstants.Claims.Subject, "Testing")
};
foreach (var claim in claims)
claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken);
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "OpenIddict"));
return SignIn(principal, OpenIddictServerDefaults.AuthenticationScheme);
}
[Authorize, HttpGet("~/api/test")]
public IActionResult GetMessage()
{
return Json(new
{
Subject = User.GetClaim(OpenIdConnectConstants.Claims.Subject),
Id = User.GetClaim(ClaimsConstants.Id),
Temp= User.GetClaim(ClaimsConstants.Temp)
});
}
}发布于 2019-02-25 12:49:21
在ConfigureServices方法的末尾添加以下代码行解决了此问题:
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
});https://stackoverflow.com/questions/54843659
复制相似问题