C# 没有ASP.NET标识的.NET核心外部身份验证
我使用自己的JWT令牌身份验证,而不是默认模板免费提供的asp.net标识。我到处都找过一些关于如何在没有asp.net身份的情况下实现外部身份验证的文档/指南,但是所有的文章都是关于asp.net身份验证的 我已经设法将用户重定向到google登录页面(使用ChallengeResult),但当提供商重定向回应用程序时,我失败了 我已删除:app.UseAuthentication()在Startup.cs中(禁用身份验证),然后我能够访问回调函数,但是我不知道如何在不使用登录管理器的情况下从响应中检索数据 启动C# 没有ASP.NET标识的.NET核心外部身份验证,c#,.net,asp.net-core,oauth-2.0,asp.net-identity,C#,.net,Asp.net Core,Oauth 2.0,Asp.net Identity,我使用自己的JWT令牌身份验证,而不是默认模板免费提供的asp.net标识。我到处都找过一些关于如何在没有asp.net身份的情况下实现外部身份验证的文档/指南,但是所有的文章都是关于asp.net身份验证的 我已经设法将用户重定向到google登录页面(使用ChallengeResult),但当提供商重定向回应用程序时,我失败了 我已删除:app.UseAuthentication()在Startup.cs中(禁用身份验证),然后我能够访问回调函数,但是我不知道如何在不使用登录管理器的情况下从
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Authentication:Secret"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = Configuration["Urls:Base"],
ValidateAudience = true,
ValidAudience = Configuration["Urls:Base"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenValidationParameters;
}
).AddGoogle(googleOptions =>
{
googleOptions.ClientId = "x";//Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = "x";//Configuration["Authentication:Google:ClientSecret"];
googleOptions.CallbackPath = "/api/authentication/externalauthentication/externallogincallback";
});
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("sv")
};
opts.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
});
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.RegisterAppSettings(Configuration);
services.AddOptions();
services.InjectServices();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
EndpointsAppSettings endpointAppSettings = new EndpointsAppSettings();
Configuration.GetSection("Endpoints").Bind(endpointAppSettings);
app.UseCors(builder =>
{
builder.WithOrigins(endpointAppSettings.Aurelia)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
}
var logService = app.ApplicationServices.GetService<ILogService>();
loggerFactory.AddProvider(new LogProvider(logService));
app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenValidationParameters;
})
.AddCookie()
.AddGoogle(googleOptions =>
{
googleOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
googleOptions.ClientId = "x";//Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = "x";//Configuration["Authentication:Google:ClientSecret"];
//googleOptions.CallbackPath = "/api/authentication/externalauthentication/signin-google";
});
公共类启动
{
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfigurationRoot配置{get;}
public void配置服务(IServiceCollection服务)
{
var signingKey=new-SymmetricSecurityKey(Encoding.ASCII.GetBytes(配置[“身份验证:机密]);
var tokenValidationParameters=新的tokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=签名密钥,
validateisuer=true,
validisuser=Configuration[“url:Base”],
ValidateAudience=true,
validudience=Configuration[“url:Base”],
ValidateLifetime=true,
时钟偏移=时间跨度0
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o=>
{
o、 TokenValidationParameters=TokenValidationParameters;
}
).AddGoogle(谷歌选项=>
{
googleOptions.ClientId=“x”//Configuration[“Authentication:Google:ClientId”];
googleOptions.ClientSecret=“x”//配置[“身份验证:Google:ClientSecret”];
googleOptions.CallbackPath=“/api/authentication/externalauthentication/externallogincallback”;
});
服务。配置(
选项=>
{
var supportedCultures=新列表
{
新文化信息(“en”),
新文化信息(“sv”)
};
opts.DefaultRequestCulture=newrequestculture(culture:“en”,uiCulture:“en”);
opts.SupportedCultures=SupportedCultures;
opts.supporteduccultures=支持的文化;
});
services.AddMvc(配置=>
{
var policy=new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()文件
.Build();
config.Filters.Add(新的授权过滤器(策略));
});
服务。注册应用程序设置(配置);
services.AddOptions();
services.InjectServices();
}
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
app.UseAuthentication();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
EndpointsAppSettings endpointAppSettings=新的EndpointsAppSettings();
Configuration.GetSection(“Endpoints”).Bind(endpointAppSettings);
app.UseCors(builder=>
{
builder.WithOrigins(endpointAppSettings.Aurelia)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
}
var logService=app.ApplicationServices.GetService();
AddProvider(新的LogProvider(logService));
app.UseRequestLocalization(app.ApplicationServices.GetService().Value);
app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
控制器
[Route("api/authentication/[controller]")]
public class ExternalAuthenticationController : Controller
{
[AllowAnonymous]
[HttpPost(nameof(ExternalLogin))]
public IActionResult ExternalLogin(ExternalLoginModel model)
{
if (model == null || !ModelState.IsValid)
{
return null;
}
var properties = new AuthenticationProperties { RedirectUri = "http://localhost:3000/#/administration/organisations" };
return Challenge(properties, model.Provider);
}
[AllowAnonymous]
[HttpGet(nameof(ExternalLoginCallback))]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
return null;
}
//Help me retrieve information here!
return null;
}
}
[AllowAnonymous]
[HttpPost(nameof(ExternalLogin))]
public IActionResult ExternalLogin(ExternalLoginModel model)
{
if (model == null || !ModelState.IsValid)
{
return null;
}
var properties = new AuthenticationProperties { RedirectUri = _authenticationAppSettings.External.RedirectUri };
return Challenge(properties, model.Provider);
}
[AllowAnonymous]
[HttpGet(nameof(ExternalLoginCallback))]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
//Here we can retrieve the claims
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return null;
}
[路由(“api/authentication/[controller]”)
公共类ExternalAuthenticationController:控制器
{
[异名]
[HttpPost(名称(外部登录))]
公共IActionResult外部登录(外部登录模型)
{
if(model==null | |!ModelState.IsValid)
{
返回null;
}
var properties=newauthenticationproperties{RedirectUri='http://localhost:3000/#/administration/organisations" };
返回质询(属性、模型、提供程序);
}
[异名]
[HttpGet(name of(ExternalLoginCallback))]
公共异步任务ExternalLoginCallback(string returnUrl=null,string remoteError=null)
{
if(remoteError!=null)
{
返回null;
}
//帮我在这里检索信息!
返回null;
}
}
外部LoginCallback的堆栈跟踪
信息:Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
请求启动HTTP/1.1获取数据——52462e4156a..5code&prompt=none
失败:Microsoft.AspNetCore.Server.Kestrel[13]
连接id“0HLAKEGSHERH7”,请求id“0HLAKEGSHERH7:00000002”:应用程序引发了未经处理的异常。
System.InvalidOperationException:未配置IAAuthenticationSignInHandler来处理方案:承载的登录
在Microsoft.AspNetCore.Authentication.AuthenticationService.d_u13.MoveNext()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
位于Microsoft.AspNetCore.Authentication.Remote