Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I retrieve userinfo from bearer token on server side -- web api 2?

Here is my scenario: I have a MVC web application and Web API. Web application making calls to web api for saving/retrieving data from server.

Lets say this is a question/answer web site. Right now I have an API that gives me userid if I provide username, password. But there are other areas in the website and its easy to retrieve other user's userid. I'm keeping the userid in the session storage and sending that in the POST object wherever required. Now any user can tweak that userid in the session storage and they can post the question/answer on behalf of other user.

How I can prevent this? One approach I was thinking but not sure if this is feasible solution - can we retrieve the userid from the supplied bearer token on the server side?

like image 448
Pritam Karmakar Avatar asked Mar 22 '15 16:03

Pritam Karmakar


People also ask

Where are bearer tokens stored?

There are two patterns for client-side storage of bearer tokens: cookies and using HTML5 local storage. If cookies are being used to transmit the bearer token from client to server, then cookies would also be used to store the bearer token on the client side.

Where are Web API tokens stored?

By default the token is not stored by the server. Only your client has it and is sending it through the authorization header to the server. If you used the default template provided by Visual Studio, in the Startup ConfigureAuth method the following IAppBuilder extension is called: app.


1 Answers

Sure you can do this, once you establish token based authentication in Web API using the resource owner credential flow, and when you attribute you protected controllers with [Authorize]. The valid bearer token you will send to this protected endpoint will create ClaimsPrincipal principal (identity) object where the user is stored in it, you can get the username as the below:

[RoutePrefix("api/Orders")]
public class OrdersController : ApiController
{
    [Authorize]
    [Route("")]
    public IHttpActionResult Get()
    {
        ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

        var Name = ClaimsPrincipal.Current.Identity.Name;
        var Name1 = User.Identity.Name;

        return Ok();
    }

}

For more detailed information about this you can read my detailed posts about this topic here.

like image 106
Taiseer Joudeh Avatar answered Oct 19 '22 06:10

Taiseer Joudeh