9

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?

Pritam Karmakar
  • 2,773
  • 5
  • 30
  • 49

1 Answers1

16

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Taiseer Joudeh
  • 8,953
  • 1
  • 41
  • 45
  • Hi Taiseer- thanks for your answer. I really liked your blog and learning new stuff regarding Web API. For this question - Getting this error message - 'System.Net.Http.HttpRequestMessage' does not contain a definition for 'GetRequestContext'. Really appreciate if you can provide some inputs. – Pritam Karmakar Apr 22 '15 at 15:13
  • Previous issue resolved by adding the missing namespace found answer here http://stackoverflow.com/questions/27897235/couldnt-find-getrequestcontext-in-system-net-http-httprequestmessage – Pritam Karmakar Apr 22 '15 at 16:14
  • One last thing to check..I want to add a new claim identity like ClientId in "GrantResourceOwnerCredentials" method. I did that but if I read ClaimsPrincipal it doesn't have that. – Pritam Karmakar Apr 22 '15 at 16:15
  • I am getting Null in User.Identity.Name; Please advise. – Saurabh Aug 21 '17 at 09:15
  • @Saurabh please check this: https://stackoverflow.com/questions/26046441/current-user-in-owin-authentication/26047766#26047766 maybe you forgot to set the correct claim – Taiseer Joudeh Aug 21 '17 at 16:19
  • @TaiseerJoudeh - Thanks for response. My web client and api are in different server, still above approach work or not ? – Saurabh Oct 16 '17 at 07:02