c# - ASP.NET Identity is null even the token is sent -
for thesis project have implement token-based (bearer) authentication in asp.net solution. implemented taiseer jouseh (http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity).
the basic part working correctly. have mobile client on can register new user. can login , receive token. when make request, token sent in request header. works fine. problem is, 401 unauthorized error if call [authorize] method, if send token. removed [authorize] annotation test things:
var z = user.identity; var t = thread.currentprincipal.identity; var y = httpcontext.current.user.identity; var x = request.getowincontext().authentication.user.identity;
here got alwas same identity: authenticationtype=null; isauthenticated=false; name=null; claims:empty
var token = request.headers.authorization;
here right token. token sent request.
i hope can me. have token no identity.
here parts of code: oauthserviceprovider:
public class simpleauthorizationserverprovider : oauthauthorizationserverprovider { public async override task validateclientauthentication(oauthvalidateclientauthenticationcontext context) { context.validated(); } // post /token public override async task grantresourceownercredentials(oauthgrantresourceownercredentialscontext context) { context.owincontext.response.headers.add("access-control-allow-origin", new[] { "*" }); var usermanager = dependencyresolver.current.getservice<usermanager<identityuser, int>>(); identityuser user = await usermanager.findasync(context.username, context.password); if (user == null) { context.seterror("invalid_grant", "the user name or password incorrect."); return; } var identity = await usermanager.createidentityasync(user, context.options.authenticationtype); identity.addclaim(new claim("sub", context.username)); identity.addclaim(new claim("role", "user")); context.validated(identity); } }
the controller method:
#region /user/:id [httpget] [route("{id:int:min(1)}")] [responsetype(typeof(usereditdto))] public async task<ihttpactionresult> getuser(int id) { try { // tests var z = user.identity; var t = thread.currentprincipal.identity; var y = httpcontext.current.user.identity; var x = request.getowincontext().authentication.user.identity; var token = request.headers.authorization; user user = await _usermanager.findbyidasync(id); if (user == null) { return notfound(); } mapper.createmap<user, usereditdto>(); return ok(mapper.map<usereditdto>(user)); } catch (exception exception) { throw; } } #endregion
the webapiconfig:
public static class webapiconfig { public static void register(httpconfiguration config) { config.suppressdefaulthostauthentication(); config.filters.add(new hostauthenticationfilter("bearer")); config.maphttpattributeroutes(); var corsattr = new enablecorsattribute("*", "*", "*"); config.enablecors(corsattr); config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); } }
startup:
[assembly: owinstartup(typeof(startup))] public class startup { public void configuration(iappbuilder app) { httpconfiguration config = new httpconfiguration(); var container = new unitycontainer(); unityconfig.registercomponents(container); config.dependencyresolver = new unitydependencyresolver(container); //config.dependencyresolver = new unityhierarchicaldependencyresolver(container); webapiconfig.register(config); app.usewebapi(config); configureoauth(app); } public void configureoauth(iappbuilder app) { oauthauthorizationserveroptions oauthserveroptions = new oauthauthorizationserveroptions() { allowinsecurehttp = true, tokenendpointpath = new pathstring("/token"), accesstokenexpiretimespan = timespan.fromdays(1), provider = new simpleauthorizationserverprovider() }; // token generation app.useoauthbearerauthentication(new oauthbearerauthenticationoptions()); app.useoauthauthorizationserver(oauthserveroptions); } }
finally found problem. simple, can't believe spent more week solve problem.
the problem in startup. had call configureoauth(app);
before app.usewebapi(config);
so correct startup looks like
[assembly: owinstartup(typeof(startup))] public class startup { public void configuration(iappbuilder app) { httpconfiguration config = new httpconfiguration(); var container = new unitycontainer(); unityconfig.registercomponents(container); config.dependencyresolver = new unitydependencyresolver(container); //config.dependencyresolver = new unityhierarchicaldependencyresolver(container); webapiconfig.register(config); configureoauth(app); app.usewebapi(config); } public void configureoauth(iappbuilder app) { oauthauthorizationserveroptions oauthserveroptions = new oauthauthorizationserveroptions() { allowinsecurehttp = true, tokenendpointpath = new pathstring("/token"), accesstokenexpiretimespan = timespan.fromdays(1), provider = new simpleauthorizationserverprovider() }; // token generation app.useoauthbearerauthentication(new oauthbearerauthenticationoptions()); app.useoauthauthorizationserver(oauthserveroptions); } }
Comments
Post a Comment