I User Net Core 3.1 i Rdzeń EF do tożsamości i logowania. Początkowo używam metody haseł do podpisania i zwrócenia sukcesu po tym, że retdirecttoakcja do "profilu".

W "profilu" user.identity

Jak widać w moim kodzie, który uruchomiłem Zaloguj się Kompletny i działa poprawnie. Ale użytkownik nie jest autentyczny. Oto mój log:

[HttpPost]
    public async Task<IActionResult> SignUp(string username, string password)
    {
        var user = _db.Users.Where(p => p.UserName == username).FirstOrDefault();
        if (user != null)
        {
            var res = await _signInManager.PasswordSignInAsync(user, password, true, false);
            if (res.Succeeded)
            {

                return RedirectToAction("profile");


            }

        }


        return View();
    }

A oto profil:

public IActionResult Profile()
    {
        var t = User.Identity.IsAuthenticated;
        var n = User.Identity.Name;
        var s = User.Claims.ToList();
        var x = _userManager.GetUserId(User);

        var ss = User.IsInRole("Admin");
        return View();
    }

A oto mój start:

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

        services.AddDbContext<MyContext>(opt =>
        {
            opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString("DefaultConnection")));
        });

        var builder = services.AddIdentityCore<User>();
        var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
        identityBuilder.AddRoles<UserRole>();
        identityBuilder.AddEntityFrameworkStores<MyContext>();
        identityBuilder.AddSignInManager<SignInManager<User>>();
        services.ConfigureApplicationCookie(options =>
        {

            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/AccessDenied";
            options.SlidingExpiration = true;
        });
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie("Identity.Application");
    }
 
    // 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.UseStaticFiles();


        app.UseRouting();
        app.UseAuthentication();

        app.UseAuthorization();

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

Uruchomienie aktualizacji

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<MyContext>(opt =>
        {
            opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString("DefaultConnection")));
        });

        var builder = services.AddIdentityCore<AppUser>();
        var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
        identityBuilder.AddRoles<Role>();
        identityBuilder.AddEntityFrameworkStores<MyContext>().AddDefaultTokenProviders();
        identityBuilder.AddSignInManager<SignInManager<AppUser>>();

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

        services.Configure<IdentityOptions>(options =>
        {
            options.SignIn.RequireConfirmedEmail = false;
            options.SignIn.RequireConfirmedAccount = false;
            options.SignIn.RequireConfirmedPhoneNumber = false;
        });
        

      


        
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie("Identity.Application");
    
        services.AddMvc();
    }

    // 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.UseStaticFiles();


        app.UseRouting();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "Admin",
                pattern: "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
0
siyavash 23 listopad 2020, 11:38

1 odpowiedź

Najlepsza odpowiedź

Wreszcie rozwiązuję problem z pomocą @Yinqiu i trochę więcej wyszukiwania. Dodam te linie do logowania metody:

    var claims = new[] 
{ 
    new Claim("name", authUser.Username)
};

    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

Nie mam pojęcia o tym, jak rozwiązuje, ale działa.

Oczywiście zmieniam linię w klasie uruchamiania:

... .AddCookie("Cookie");
0
siyavash 26 listopad 2020, 06:47