简体   繁体   中英

HttpContext.Current.User.Identity.Name is null after setting custom principal in GrantResourceOwnerCredentials in my owin authorization provider

Here is my GrantResourceOwnerCredentials method:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        AccountModels.UserProfile user = ApplicationUserManager.UserLogin(new AccountModels.LoginModel { UserName = context.UserName , Password = context.Password, RememberMe= false });

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
        else
        {
            if (user.IsLoggedIn = false)
            {
                context.SetError("invalid_grant", "The user is no longer active. Please contact support for account activation");
                return;
            }
            else
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRole));


                var roles = new string[] {user.UserRole};

                AuthenticationProperties properties = CreateProperties(user.UserName, roles, user.IsEmilConfirmed);
                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

                context.Validated(ticket);

                MyCustomPrincipal newUser = new MyCustomPrincipal(user.UserName);
                newUser.Id = user.UserID;
                newUser.Email = user.UserName;
                newUser.Role = user.UserRole;

                SetPrincipal(newUser);
                context.Request.Context.Authentication.SignIn(identity);

            }
        }
    }

I had to implement a custom login logic to support my old database schema and after login i wanted to set the just logged in user in httpcontext.current.user.

Here is my SetPrincipal method:

private static void SetPrincipal(IPrincipal principal)
    {
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }
    }

After authorization whenever i call HttpContext.Current.User.Identity.Name in a controller i get null value. What am i missing here? Can anyone give me any idea?

Try using the User object in your controller:

var principal = User as ClaimsPrincipal;

Side note: call to SetPrincipal is not necessary in the GrantResourceOwnerCredentials if you are using OWIN hosting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM