我刚刚将我的 dotnet core webapi 应用程序从netcoreapp1.0更新为netcoreapp2.0。我正在使用 openiddict 基于此示例进行身份验证和授权。
配置服务方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(@"Server=SERVER1;Database=DB1;User Id=BLAHBLAH;Password=BLAHBLAHBLAH;");
options.UseOpenIddict();
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
services.AddOpenIddict(options =>
{
options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
options.AddMvcBinders();
options.EnableTokenEndpoint("/connect/token");
options.AllowPasswordFlow();
options.DisableHttpsRequirement();
options.SetAccessTokenLifetime(TimeSpan.FromMinutes(5));
});
services.AddAuthentication()
.AddOAuthValidation();
}
配置方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(b => b.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseOpenIdConnectServer(configuration => {
configuration.AllowInsecureHttp = true;
configuration.Provider = new AuthorizationProvider();
});
app.UseAuthentication();
app.UseMvc();
}
AuthorizationProvider类:
public sealed class AuthorizationProvider : OpenIdConnectServerProvider
{
public AuthorizationProvider()
{
}
public override async Task ApplyTokenResponse(ApplyTokenResponseContext context)
{
if (string.IsNullOrEmpty(context.Error))
{
var role = context.Ticket.Principal.Claims.FirstOrDefault(q => q.Type == OpenIdConnectConstants.Claims.Role).Value;
var userName = context.Ticket.Principal.Claims.FirstOrDefault(q => q.Type == OpenIdConnectConstants.Claims.Name).Value;
context.Response["role"] = role;
context.Response["userName"] = userName;
context.Response[".issued"] = DateTime.Now.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");
context.Response[".expires"] = DateTime.Now.AddHours(8).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");
}
return;
}
}
以下代码不起作用:
app.UseOpenIdConnectServer(configuration => {
configuration.AllowInsecureHttp = true;
configuration.Provider = new AuthorizationProvider();
});
它说“IApplicationBuilder”不包含“UseOpenIdConnectServer”的定义,并且找不到接受“IApplicationBuilder”类型的第一个参数的扩展方法“UseOpenIdConnectServer”(您是否缺少 using 指令或程序集引用?)
我该如何解决?添加自定义提供程序的替代方法是什么?