W
W
WhiteNinja2017-01-08 23:49:43
ASP.NET
WhiteNinja, 2017-01-08 23:49:43

How to properly add my properties to custom IIdentity ASP.NET (OWIN)?

Good afternoon! I ask for help in building authorization / authentication in an application without using ASP.NET Identity, but using OWIN.
An ASP.NET MVC 5 application has a LogIn method :

[HttpPost]
public ActionResult LogIn(LoginVM loginVM)
{
  try
  {
    if (!ModelState.IsValid)
    {
      return View(loginVM);
    }

    var user = userService.GetUser(loginVM.Email, loginVM.Password);

    if (user == null) {
      // TODO: Выводить сообщение - Неверный логин или пароль
      return View(loginVM);
    }
    
    var claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserId));
    // Также мне нужно добавить в клеймы ряд данных
    claims.Add(new Claim("Firstname", user.FirstName));
    claims.Add(new Claim("Secondname", user.SecondName));
    claims.Add(new Claim("Lastname", user.LastName));
    claims.Add(new Claim("SomeId", user.SomeId));
    claims.Add(new Claim("OneMoreId", user.SomeId));
    
    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

    AuthenticationManager.SignIn(new AuthenticationProperties()
    {
      IsPersistent = loginVM.RememberMe,
      ExpiresUtc = DateTime.UtcNow.AddDays(7)
    }, identity);

    return RedirectToAction("Index", "Home");
  }
  catch (Exception ex)
  {
    return ErrorInternal(ex);
  }
}

In it, we are looking for a user using our own userService, and in case of a successful search, we authorize the user using the OWIN mechanism, while recording additional Firstname, SomeId, etc. data.
Having honestly read all the manuals, I still have questions:
1) How to override IPrincipal / IIdentity in such a way as to add my own fields and methods to call them in views and controllers?
public class SomeController : BaseController
{
  public ActionResult Index()
  {
    ViewBag.UserName = User.Identity.SomeId; // Которые я записывал к Claims
    return View();
  }
}

and where is it better to override HttpContext.Current.User = CustomUser(CustomIPrincipal), in
AuthorizeAttribute attribute, method - AuthorizeCore, or in PostAuthenticateRequest method?
2) The second question is related to roles. Let's say there is a service method userService.Roles(int userId) that returns a list of user roles by ID. When should roles be recorded?
1 - Write to the hallmarks during authorization? (the LogIn method described above). But in this case, if the user is given new roles after authorization, they will not be available, right?
2 - Write them on each page in CustomPrincipal, for example in the AuthorizeAttribute attribute or somewhere else?
So that you can call the method anywhere in the controller or view - User.InRoles("Admin, SuperAdmin"), for example).
I really need advice on these matters!
Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kovalsky, 2017-01-09
@dmitryKovalskiy

For the first question, there is a solution the following (a crutch in my opinion, but it has happened worse) - to inherit from BaseController and create your own BaseController. You can add the CurrentUser property (for example) to it, returning your class that implements and extends IPrincipal. And the property, in turn, must be implemented as a cast of User with type IPrincipal to your class.

R
RouR, 2017-01-12
@RouR

var user = HttpContext.Current.GetOwinContext().Authentication.User;

            if (user != null)
            {
                IList<Claim> claims = user.Claims.ToList();

                Claim clientIdClaim = claims.FirstOrDefault(x => x.Type == "SomeId");

                if (clientIdClaim != null)
                {
                    string clientId = clientIdClaim.Value;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question