声明GetUserId为null

时间:2015-03-07 02:32:30

标签: asp.net-mvc asp.net-web-api asp.net-identity owin

我希望你们都很棒,这次我在这里问一个我无法弄明白的问题而且这是关于身份的问题,我想要的是从声明校长那里得到用户ID,或者不管它是什么,现在我唯一拥有的是

var principal = ClaimsPrincipal.Current;
        var id1 = principal.Claims.FirstOrDefault(c => c.ValueType == ClaimTypes.NameIdentifier);

但是当我尝试获取UserId并且我转到声明中的信息时,即使我在登录时将其保存在AuthorizationTicket中,我也无法找到该值。

我正在使用MVC模板和Web api服务我的服务托管在IIS中,通过令牌我使用帐户控制器管理身份验证

这是我的AuthenticationProperties

public static AuthenticationProperties CreateProperties(string userName, string userid)
    {
        IDictionary<string, string> data = new Dictionary<string, string> { { "userName", userName }, { "userId", userid } };
        return new AuthenticationProperties(data);
    }

和我的GrantResourceOwnerCredentiales

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
        //var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>();

        AppJobSeeker user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(user.UserName, user.Id);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);...

我有一个创建AuthenticationTicket的方法,它也接收UserName和UserId

private void CreateTicket(SignInResult result, SignInModel model, string returnUrl)
    {
        //Let's keep the user authenticated in the MVC webapp.
        //By using the AccessToken, we can use User.Identity.Name in the MVC controllers to make API calls.
        FormsAuthentication.SetAuthCookie(result.AccessToken, model.RememberMe);

        //Create an AuthenticationTicket to generate a cookie used to authenticate against Web API.
        //But before we can do that, we need a ClaimsIdentity that can be authenticated in Web API.
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, result.UserName), //Name is the default name claim type, and UserName is the one known also in Web API.
            new Claim(ClaimTypes.NameIdentifier, result.UserId), //If you want to use User.Identity.GetUserId in Web API, you need a NameIdentifier claim.
        };

        //Generate a new ClaimsIdentity, using the DefaultAuthenticationTypes.ApplicationCookie authenticationType.
        //This also matches what we've set up in Web API.
        var authTicket = new AuthenticationTicket(new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie), new AuthenticationProperties
        {
            ExpiresUtc = result.Expires,
            IsPersistent = model.RememberMe,
            IssuedUtc = result.Issued,
            RedirectUri = returnUrl
        });

...

当我登录时,Everithing看起来很好但是当我去另一个控制器时,我无法撤回UserId

1 个答案:

答案 0 :(得分:1)

您是否已将 [授权] 属性添加到控制器中?

[Authorize]
public class AuthorizeController : ApiController
{
   public Task<IHttpActionResult> GetUserId()
   {
       return Ok(HttpContext.Current.User.Identity.GetUserId());
   }
}