在ASP.Net Core 2中使用Cookie(无数据库)进行Google身份验证

时间:2018-03-07 01:50:46

标签: asp.net asp.net-mvc asp.net-core asp.net-core-mvc google-oauth

我想使用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登录页面。

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

我的问题似乎是因为我在UseAuthentication

之后放了UseMvc