Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api User Identity returning null

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?

like image 486
Dominick Piganell Avatar asked Nov 10 '22 07:11

Dominick Piganell


1 Answers

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));
like image 82
hvaughan3 Avatar answered Nov 15 '22 08:11

hvaughan3