shaahin
shaahin

Reputation: 108

Angular2 + Web API + token based authentication

I am trying to learn Angular2

and I am trying to create a simple blog with authentication.

this here is my add a new post method:

    [Authorize]
    // POST: api/Post
    public PostModel Post([FromBody]PostViewModel model)
    {             
        var post = new PostModel
        {
            Body = model.Body,
            Title = model.Title,
            AuthorId = IdentityExtensions.GetUserId(User.Identity),
        };
        var res = blogRepo.AddPost(post);
        return res;                 
    }

everything works fine, but IdentityExtension.GetUserId() do not return the most current logged in user but the first user since the app started.

basically I am looking for a way to make sure that the current user logs out on the server as well as on the client (the client side is just a simple removal of the localStorage.removeItem("jwt");)

also there is a good chance that what I am doing is totally wrong, but I can't access the ApplicationUserManager in this controller.

Upvotes: 2

Views: 1779

Answers (1)

shaahin
shaahin

Reputation: 108

ok I have found the problem, although I haven't managed to solve it yet but I will update this when i do, and I am writing this as an answer since the problem is totally different from what I asked and thought to be.

the problem is related to sending the authentication hints as Thierry Templier suggested. I have a file that exports headers like this:

  export const authHeaders = new Headers();
    authHeaders.append('Accept', 'application/json');
    authHeaders.append('Content-Type', 'application/json');
    authHeaders.append('Authorization', 'Bearer ' + localStorage.getItem('jwt'));

And I Import this header where ever I need it. but I am not sure why it always sends a cached value (i.e the first value stored on the client and it has nothing to do with the server side as my question implies).

to solve this issue I just have to make sure the latest access-token stored on localstorage is sent to the server.

EDIT: for now I am constructing the headings in the constructor.

Upvotes: 1

Related Questions