HttpContext.SignInAsync()无法设置cookie并返回User.Identity.IsAuthenticated为true [英] HttpContext.SignInAsync() fails to set cookie and return User.Identity.IsAuthenticated as true

查看:460
本文介绍了HttpContext.SignInAsync()无法设置cookie并返回User.Identity.IsAuthenticated为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个网站,该网站将执行Discord的SSO.我正在尝试通过cookie来仅使用该登录系统.我似乎无法设置cookie并返回 User.Identity.IsAuthenticated; 为true.当我使用F12查看浏览器时,cookie不存在.我不确定为什么登录后未将cookie发送给用户.我在Startup.cs和我的登录文件下面提供了该cookie.预先谢谢你!

I wrote a website that will do a SSO from Discord. I am trying to do a login system using only that by way of cookies. I seem to not be able to set the cookie and return User.Identity.IsAuthenticated; as true. When I look at the browser using F12, the cookie is not present. I am unsure why the cookie is not being sent to the user after logging in. I have provided below the Startup.cs and my login file. Thank you in advance!


    public class SigninController : Controller
        {
            private ApplicationDbContext _context;

            public SigninController(ApplicationDbContext context)
            {
                _context = context;
            }

            [AllowAnonymous]
            public async Task<RedirectToActionResult> SaveRegistration(RegistrationViewModel pageData)
            {
                var debug = User.Identity.IsAuthenticated;
                if (pageData.Tribe == null)
                {
                    pageData.Tribe = "Solo";
                }
                //Create the nomad
                var nomad = new Nomad
                {
                    Name = pageData.Name,
                    Role = "user",
                    Snowflake = pageData.Snowflake,
                    Tribe = pageData.Tribe
                };

                //Add and save the nomad to the database
                _context.Nomads.Add(nomad);
                await _context.SaveChangesAsync();

                //Generate the claims
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, nomad.Name));
                claims.Add(new Claim("Snowflake", nomad.Snowflake.ToString()));
                claims.Add(new Claim("Tribe", nomad.Tribe));
                claims.Add(new Claim(ClaimTypes.Role, nomad.Role));

                //Generate the user's cookie!
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties { IsPersistent = true };
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new         ClaimsPrincipal(claimsIdentity), authProperties);

                debug = User.Identity.IsAuthenticated;

                return RedirectToAction("Index", "Home", new {Area = ""});
            }
    }


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Last_Oasis_Web_Suite.Data;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;

    namespace A_Name_Space
    {
        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.AddControllersWithViews();
                services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(
                            Configuration.GetConnectionString("DefaultConnection")));




                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => false;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });

                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options =>
                    {
                        options.Cookie.HttpOnly = true;
                        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                        options.Cookie.SameSite = SameSiteMode.None;
                        options.Cookie.Name = "Cookie";
                        options.LoginPath = "/Discord/Signin/Redirect";
                        options.LogoutPath = "/Discord/Signout";
                    });


                services.AddControllers(config =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                });
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                app.UseCookiePolicy();

                app.UseStaticFiles();

                app.UseRouting();

                app.UseAuthentication();
                app.UseAuthorization();

                app.UseEndpoints(endpoints =>
                {
                                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

推荐答案

答案是,我没有配置为在ASP.NET中使用HTTPS,因此cookie永远不会发送到浏览器.我重新制作了项目,并选中了强制使用HTTPS的框,一切正常.我假设没有安全的连接来发送加密的数据,它决定不发送该数据.

The answer is that I was not configured to use HTTPS in ASP.NET so the cookies were never getting sent to the browser. I remade my project and checked the box to force HTTPS and everything worked fine, as is. I'll assume without a secure connection to send the encrypted data, it decides to just not send it.

这篇关于HttpContext.SignInAsync()无法设置cookie并返回User.Identity.IsAuthenticated为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆