Search code examples
c#asp.net-mvcowin

How to get the logged user with an OWIN authentication?


The login code in my AccountController

var claims = new List<Claim>();  
claims.Add(new Claim(ClaimTypes.Name, user.Name+" "+user.Surname));
claims.Add(new Claim(ClaimTypes.Role, role.Code));
var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, claimIdenties);

In my PrivateController I want to access to the Id of the authenticated user, I'm searching an ID field or something like that but

enter image description here

How to get the logged user with an OWIN authentication?

Edit

Request.GetOwinContext().Authentication.User.Identity

Gives me access to the following propertys:

  • AuthenticationType
  • IsAuthenticated
  • Name //Claim.Name

How can I set an ID like a 'Claim.ID' and retrieve it?

Second edit

This post https://stackoverflow.com/a/24893167/4470880 solved my problem.


Solution

  • Try this alternative:

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

    For getting name of the `user`:
    string name = HttpContext.GetOwinContext().Authentication.User.Identity.Name;