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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With