asp.net web api2 - Testing if a request is anonymous or authenticated WebAPI 2 + Identity -


i'm using webapi 2 + asp.net identity

in 1 of apicontroller methods, test if particular http request coming authenticated client or not (i.e. whether request contains authorization header or not).

the following works, maybe there better way?

private authcontext db = new authcontext();  // api/orders/ [allowanonymous] public async task<ihttpactionresult> getorder(int id) {     // applicationuser identityuser.     applicationuser currentuser = null;      try     {         usermanager<applicationuser> usermanager = new usermanager<applicationuser>(new userstore<applicationuser>(db));         currentuser = await usermanager.findbynameasync(user.identity.getusername());     }     catch (exception)     {     }      if ( currentuser == null )     {         // anonymous request.         // etc...         } else {         // authorized request.         // etc...     } } 

i using default routing template. option route 2 different methods authorized requests , anonymous requests (decorated appropriate data annotations).

in apicontroller class in webapi there user property (which making use of in code: user.identity.getusername()).

this user property iprincipal instance has property identity instance of iidentity.

within code of apicontroller method can test whether user current request authenticated testing isauthenticated property of user.identity.

for example:

if ( user.identity.isauthenticated == true) {     // authenticated user...do } else {    // anonymous..do different } 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -