Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access IIdentity from Web API

I'm adding some Web API services to an existing MVC application. I have a model binder for my MVC controllers to get the user object stored in a CustomIdentity. I'm trying to reproduce this for my Web API actions.

In the MVC Controller or its binders I can use

controllerContext.HttpContext.User.Identity 

The ApiController doesn't have the HttpContext object. Is there anyway to access the IIdentity object from the Web API?

like image 968
Magpie Avatar asked Mar 19 '12 10:03

Magpie


People also ask

Which authentication is best for Web API?

OAuth (specifically, OAuth 2.0) is considered a gold standard when it comes to REST API authentication, especially in enterprise scenarios involving sophisticated web and mobile applications. OAuth 2.0 can support dynamic collections of users, permission levels, scope parameters and data types.

How does token authentication work in Web API?

Token-based authentication is a process where the client application first sends a request to Authentication server with a valid credentials. The Authentication server sends an Access token to the client as a response. This token contains enough data to identify a particular user and it has an expiry time.


2 Answers

They removed GetUserPrincipal in ASP.NET MVC 4 RC. However it seems the ApiController property User has replaced this: http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.user

like image 102
mhu Avatar answered Sep 24 '22 00:09

mhu


Yes you can. ApiController has a Request property of type System.Net.Http.HttpRequestMessage; this holds details about the current request naturally (it also has a setter for unit testing purposes). HttpRequestMessage has a Properties dictionary; you will find the value of the key MS_UserPrincipal holds your IPrincipal object.

In researching this answer, I came across the System.Web.Http.HttpRequestMessageExtensions which has a GetUserPrincipal(this HttpRequestMessage request) extension method which accesses this dictionary value; I hadn't seen this extension method before and was accessing Request.Properties["MS_UserPrincipal"] directly, but this might be a better method (less dependent on the ASP.NET Web Api team keeping the name of the key the same...)

like image 32
James Webster Avatar answered Sep 23 '22 00:09

James Webster