Как использовать авторизацию без удостоверения ASP.NET - PullRequest
0 голосов
/ 16 февраля 2019

В моем проекте используйте идентификацию без идентификации Asp.net. Я делаю раздел входа в систему и хочу использовать [Authorize (Role = "...")], но я не знаю, как это сделать.

Пожалуйста, помогите мне использовать его

StartUp.cs:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            }).AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5000);
            });

Действие входа

if (ModelState.IsValid)
            {
                User user = new User();

                user = _iuser.LoginUser(login.Mobile, login.Password);

                if (user != null)
                {
                    if (user.IsActive)
                    {
                        var claims = new List<Claim>()
                        {
                            new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
                            new Claim(ClaimTypes.Name,user.Mobile)
                        };
                        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        var principal = new ClaimsPrincipal(identity);

                        var properties = new AuthenticationProperties()
                        {
                            IsPersistent = login.IsRemember
                        };

                        HttpContext.SignInAsync(principal, properties);
                        return RedirectToAction("Index", "Profile");

                    }
                    else
                    {
                        return RedirectToAction(nameof(Active));
                    }

класс пользователя:

public class User
    {
        [Key]
        public int Id { get; set; }
        public int RoleId { get; set; }
        public string Mobile { get; set; }
        public string Password { get; set; }
        public string Code { get; set; }
        public bool IsActive { get; set; }
        [ForeignKey("RoleId")]
        public virtual Role Role { get; set; }
    }

РольКласс:

public class Role
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public virtual ICollection<User> Users { get; set; }
    }

ApplicationDbContext:

public class ApplicationDbContext: DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        public DbSet<Role> Roles { get; set; }
        public DbSet<User> Users { get; set; }
    }

Подсказки: я использую ASP.NET CORE 2.2 и Entity Frame Work Core 2.2

1 Ответ

0 голосов
/ 17 февраля 2019

Существует два решения вашей проблемы:

  1. Добавить Role Claim в список заявок
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
Создать Пользовательская авторизация
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...