简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM