我使用自己的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();
}
}
控制器
[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;
}
}
ExternalLoginCallback的堆栈跟踪
info:Microsoft.AspNetCore.Hosting.Internal.WebHost [1] 请求启动HTTP / 1.1 GET http://localhost:5000/api/authentication/externalauthentication/externallogincallback?state=CfDJ8CyKJfDTf--HIDDEN DATA - 52462e4156a..5cde&amp; prompt = none 失败:Microsoft.AspNetCore.Server.Kestrel [13] 连接ID&#34; 0HLAKEGSHERH7&#34;,请求ID&#34; 0HLAKEGSHERH7:00000002&#34;:应用程序抛出了未处理的异常。 System.InvalidOperationException:没有IAuthenticationSignInHandler配置为处理该方案的登录:Bearer 在Microsoft.AspNetCore.Authentication.AuthenticationService.d__13.MoveNext() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler d__12.MoveNext() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.d__6.MoveNext() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.d__2.MoveNext()
答案 0 :(得分:3)
解决:
没有IAuthenticationSignInHandler配置为处理登录 计划:持票人
我必须添加一个cookie处理程序,它将临时存储外部身份验证的结果,例如:由外部提供商发送的声明。这是必要的,因为在完成外部身份验证过程之前通常会涉及一些重定向。
<强>启动强>
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";
});
这里的重要部分是CookieAuthenticationDefaults.AuthenticationScheme。这是一个存储“Cookies”的字符串常量。虽然我们可以在代码中直接使用字符串“Cookies”,但使用预设常量会更安全。这是默认情况下为AddCookies
函数指定的身份验证方案名称。它可以帮助您参考cookie身份验证。
现在是时候从回调操作中的外部身份验证提供的声明中检索用户信息了。
<强>控制器强>
[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;
}
瞧!我们现在有一些用户信息可供使用!
有用的链接
http://docs.identityserver.io/en/latest/topics/signin_external_providers.html