我在这里遵循OpenIddict示例中的确切示例:https://github.com/openiddict/openiddict-core。一切正常,直到我使用AddIdentity部分。我真的需要使用身份。注释掉Identity部分将起作用,如果未注释,则我将在测试控制器的Get方法上看到404,因为它不会被授权。我正在使用.Net Core 2.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)
});
}
}
答案 0 :(得分:0)
在ConfigureServices方法的末尾添加以下代码行解决了该问题:
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
});