Can I get userinfo from a server-side carrier token - web api 2?

Here is my scenario: I have an MVC web application and a web API. The web application calls the web api to save / receive data from the server.

Let's say this is a question / answer website. Right now I have an API that gives me a user ID, if I provide a username, password. But there are other areas on the website, and it’s easy to find a different user ID. I save the user ID in the session store and send it to the POST object where necessary. Now any user can configure this user ID in the session store, and they can send a question / answer on behalf of another user.

How can I prevent this? One of the approaches that I was thinking about, but not sure, is this a possible solution - can we extract the user ID from the submitted token on the server side?

+4
source share
1 answer

Of course, you can do this as soon as you set up authentication on tokens in the web API using the stream of accounts of the owner of the resource, and when you assign protected controllers using [Authorization]. The actual carrier token that you send to this secure endpoint will create a ClaimsPrincipal main (identity) object in which the user will be stored in it, you can get the username as shown 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();
    }

}

.

+8

All Articles