Answer the question
In order to leave comments, you need to log in
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);
}
}
public class SomeController : BaseController
{
public ActionResult Index()
{
ViewBag.UserName = User.Identity.SomeId; // Которые я записывал к Claims
return View();
}
}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question