【发布时间】:2018-03-07 01:50:45
【问题描述】:
我想使用 Google 对用户进行身份验证,并使用 cookie 保持身份验证。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMediatR(typeof(UpdateClientsCommandHandler));
services
.AddEntityFrameworkSqlServer()
.AddDbContext<DbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
sqlOptions =>
{
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
sqlOptions.EnableRetryOnFailure(10, TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
options.EnableSensitiveDataLogging();
}
);
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "YourCustomScheme";
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie("YourCustomScheme")
.AddGoogle(options =>
{
options.ClientId = "client-id";
options.ClientSecret = "client-secret";
options.CallbackPath = new PathString("/AuthCallback/IndexAsync");
options.SignInScheme = "YourCustomScheme";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseAuthentication();
}
}
用户已成功重定向到 Google Auth,我可以看到创建了 cookie .AspNetCore.YourCustomScheme。但随后用户只是被重定向回 Google 登录页面。
我错过了什么吗?
【问题讨论】:
-
将 options.DefaultAuthenticateScheme 更改为 YourCustomScheme
-
@Tratcher 没有帮助 :(
-
你的控制器是什么样的?
[Authorize]? -
是的,只需在控制器上使用
[Authorize]。控制器有一个简单的动作。 -
如果将
DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme替换为DefaultScheme = "YourCustomScheme"会更好吗?另外,您是否在任何地方都有 AddIdentity,它会覆盖这些设置。
标签: asp.net asp.net-mvc asp.net-core asp.net-core-mvc google-oauth