在我的owin授权提供程序

时间:2015-06-01 11:24:21

标签: c# asp.net asp.net-web-api oauth

这是我的GrantResourceOwnerCredentials方法:

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);

            }
        }
    }

我必须实现自定义登录逻辑以支持我的旧数据库模式,登录后我想在httpcontext.current.user中设置刚刚登录的用户。

这是我的SetPrincipal方法:

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

授权后,每当我在控制器中调用HttpContext.Current.User.Identity.Name时,我都会得到null值。我在这里失踪了什么?谁能给我任何想法?

1 个答案:

答案 0 :(得分:-1)

尝试使用控制器中的User对象:

var principal = User as ClaimsPrincipal;

附注:如果您使用OWIN托管,则无需在GrantResourceOwnerCredentials中调用SetPrincipal