5

I successfully log in as a user, and the user is then able to access [Authorized] parts of the site. The username even shows up in the top right corner of the site as they are successfully authenticated. However, when I try to get the User Identity in my post to make a new event, the user is null.

Here is my login service:

login.service('loginService', function ($http, $q) {
    var deferred = $q.defer();

    this.signin = function (user) {
        var config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }

        $http.post('Token', 'grant_type=password&username='+user.UserName+'&password='+user.Password, config)
            .success(function (data) {
                window.location = "/dashboard";
            }).error(function (error) {
                deferred.reject(error);
            });

        return deferred.promise;
    }
});

And here is my post to make a new event

[Route("post")]
public HttpResponseMessage PostEvent(EventEditModel ev)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "{ }");
    }
    try
    {
        Event DBEvent;
        if (ev.EventId > 0)
        {
            DBEvent = db.Events.Find(ev.EventId);
            DBEvent.ModifiedBy = Guid.Parse(User.Identity.GetUserId());
            DBEvent.ModifiedOn = DateTime.Now;
        }
        else
        {
            DBEvent = new Event();
            string id = User.Identity.GetUserId();
            DBEvent.CreatedBy = Guid.Parse(User.Identity.GetUserId());
            DBEvent.CreatedOn = DateTime.Now;
        }

        ...
}

Should I be passing user information with every post? I'm not sure how I would even do that. Or am I just not logging a user in correctly?

Dominick Piganell
  • 704
  • 2
  • 10
  • 29

3 Answers3

1

Old question that I stumbled on and wanted to give my solution. Going off Dunc's answer and then finding this post I got the answer. In order to get something back from GetUserId() you must add a new claim using the ClaimTypes.NameIdentifier type along with the User Id you want:

ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
hvaughan3
  • 10,955
  • 5
  • 56
  • 76
0

User.Identity.GetUserId() seems to return null in Web Api. From what I can gather you should use User.Identity.GetUserName() instead.

e.g.

ApplicationUser user = UserManager.FindByName(User.Identity.GetUserName());
var userId = user.Id;
Community
  • 1
  • 1
Dunc
  • 18,404
  • 6
  • 86
  • 103
0

When creating the new ClaimsIdentity, you need to create a new Claim specifically for the name using ClaimTypes.Name.

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
Matthew Scerri
  • 215
  • 4
  • 12