T
T
Timofey2020-11-22 19:39:35
ASP.NET
Timofey, 2020-11-22 19:39:35

How to correctly register Claim for authentication?

I am writing a small application on .net core, there was a problem how to correctly register a new Claim object in the authentication to access the data, I redefined to access the username, but I need to add another password and email to add the admin panel later to the user

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Project.Models;

namespace RolesApp.Controllers
{
    public class AccountController : Controller
    {
        private ApplicationContext _context;
        public AccountController(ApplicationContext context)
        {
            _context = context;
        }
        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            if ( ModelState.IsValid)
            {
                User user = await _context.Users.FirstOrDefaultAsync(u => u.Email == model.Email);
                if (user == null)
                {
                    
                    user = new User { Email = model.Email, UserName = model.UserName,  Password = model.Password };
                    Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "user");
                    if (userRole != null)
                        user.Role = userRole;

                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    await Authenticate(user); // аутентификация

                    return RedirectToAction("Index", "Home");
                }
                else
                    ModelState.AddModelError("", "Некорректные логин/пароль/вы регистрируетесь повторно");
            }
            return View(model);
        }
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginModel model)
        {
            if (  ModelState.IsValid)
            {
                User user = await _context.Users
                    .Include(u => u.Role)
                    .FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password );
                if (user != null)
                {
                    await Authenticate(user); // аутентификация

                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "Некорректные логин и(или) пароль");
            }
            return View(model);
        }
        private async Task Authenticate(User user)
        {
            // создаем один claim
            var claims = new List<Claim>
            {
               // new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name),
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName)
            };

            var Cla = new List<Claim>{
                new Claim(ClaimTypes.Actor, user.UserName)               
            };

          // var claimCla = new ClaimsIdentity(Cla);


            // создаем объект ClaimsIdentity
            ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
                ClaimsIdentity.DefaultRoleClaimType);
            // установка аутентификационных куки
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));

            

        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
P40b0s, 2021-02-21
@timofeygusevopal

I use JWT and add them like this:

private ClaimsIdentity GetClaims(User user)
        {
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserName));
            claims.Add(new Claim(ClaimTypes.Role, user.Role));
            claims.Add(new Claim(CustomClaimsTypes.IsActive, user.IsActive.ToString()));
            return new ClaimsIdentity(claims);
        }

var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = GetClaims(user),
                    Expires = claimTime,
                    Audience = auth.Audience,
                    Issuer = auth.Issuer,
                    SigningCredentials = auth.Credentials
                };

And I get in the controller:
var name = HttpContext.User.Claims.FirstOrDefault(f => f.Type == ClaimTypes.NameIdentifier).Value;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question