SignInManager.SignInAsyn c (.....) не регистрирует меня в ASP. NET Core Blazor - PullRequest
0 голосов
/ 27 января 2020

Я учусь ASP. Net Core Blazor и SignInManager.SignInAsync, а также SignInManager.PasswordSignInAsync не регистрируют меня. Я пробовал несколько раз, но все время терпел неудачу. Я вижу, что данные есть в таблицах базы данных SQLServer. Я не вижу пароль, но есть учетная запись пользователя. Я провел несколько дней, но не смог разобраться

Вот мой код

Компонент страницы входа

@page "/loginPage"

@using Microsoft.AspNetCore.Identity;
@using Microsoft.AspNetCore.Authentication;

@using GroupMembersInfo.Data;

@inject UserManager<IdentityUser> UserManager
@inject SignInManager<IdentityUser> SignInManager
@inject NavigationManager NavigationManager

<h3>Log In</h3>

<div class="row">
    <div class="col-md-12">
        <EditForm Model="@LoginUserModel" OnValidSubmit="@LogIn">
            <DataAnnotationsValidator />
            <ValidationSummary />
            <div class="form-group">
                <label>User Id: </label>
                <input @bind-value="LoginUserModel.Email" class="form-control" />
            </div>
            <div class="form-group">
                <label>Password: </label>
                <input @bind-value="LoginUserModel.Password" class="form-control" />
            </div>
            <div class="form-group">
                <button type="submit">Login</button>
            </div>
        </EditForm>
    </div>
</div>

@code {
    public LoginUserModel LoginUserModel { get; set; } = new LoginUserModel();

    public async Task LogIn()
    {
        var user = new IdentityUser
        {
            UserName = LoginUserModel.Email,
            Email = LoginUserModel.Email
        };

        user.PasswordHash = SignInManager.UserManager.PasswordHasher.HashPassword(user, LoginUserModel.Password);

        AuthenticationProperties properties = new AuthenticationProperties();
        properties.IsPersistent = true;

        await SignInManager.SignInAsync(user, properties).ContinueWith(p =>
        {
            var User = System.Security.Claims.ClaimsPrincipal.Current;
            NavigationManager.NavigateTo("/");
        });

        //var result = await SignInManager.PasswordSignInAsync(user, LoginUserModel.Password, isPersistent: false, lockoutOnFailure: false);

        //if (result.Succeeded)
        //{
        //    var User = System.Security.Claims.ClaimsPrincipal.Current;
        //    NavigationManager.NavigateTo("/");
        //}
    }
}

автозагрузка. cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using GroupMembersInfo.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;

namespace GroupMembersInfo
{
    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.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("GMIDbConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 2;
                options.Password.RequireDigit = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
            }).AddEntityFrameworkStores<AppDbContext>();

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
            services.AddSingleton<WeatherForecastService>();

            services.ConfigureApplicationCookie(options =>
            {
                options.SlidingExpiration = true;

                options.Events.OnRedirectToLogin = cxt =>
                {
                    cxt.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };

                options.Events.OnRedirectToAccessDenied = cxt =>
                {
                    cxt.Response.StatusCode = 403;
                    return Task.CompletedTask;
                };

                options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
            });
        }

        // 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("/Error");
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

1 Ответ

0 голосов
/ 27 января 2020

Почему бы просто не войти в систему с указанным адресом электронной почты и паролем?

public async Task LogIn()
{
    var result = await SignInManager.PasswordSignInAsync(LoginUserModel.Email, LoginUserModel.Password, isPersistent: false, lockoutOnFailure: false);

    if (result.Succeeded)
    {
        NavigationManager.NavigateTo("/");
    }
}
...