asp.net web api - Get bearer token from OWIN Cookie and put it on API Requests -
here scenario: have mvc4.5/webapi2 application uses openidconnectauthentication based on thinktecture.identityserver provider. far can authenticate against mvc. want authenticate webapi using bearer token. here configuration
app.usewebapi(configureapi()); app.usecookieauthentication(new cookieauthenticationoptions() { authenticationtype = cookieauthenticationdefaults.authenticationtype, cookiesecure = cookiesecureoption.always, authenticationmode = microsoft.owin.security.authenticationmode.active, cookiehttponly = true }); app.useidentityserverbearertokenauthentication(new identityserverbearertokenauthenticationoptions() { enablevalidationresultcache = false, authority = webconfigurationmanager.appsettings["authority"], authenticationmode = microsoft.owin.security.authenticationmode.passive }); app.useopenidconnectauthentication(new openidconnectauthenticationoptions() { authority = webconfigurationmanager.appsettings["authority"], clientid = webconfigurationmanager.appsettings["clientid"], clientsecret = webconfigurationmanager.appsettings["clientsecret"], responsetype = "code id_token", scope = "openid email profile", signinasauthenticationtype = cookieauthenticationdefaults.authenticationtype, notifications = new openidconnectauthenticationnotifications { authenticationfailed = onauthenticationfailed, authorizationcodereceived = onauthorizationcodereceived, redirecttoidentityprovider = onredirecttoidentityprovider } }; );
and webapi configuration
public httpconfiguration configureapi() { var httpconfig = new httpconfiguration(); // configure web api use bearer token authentication. httpconfig.suppressdefaulthostauthentication(); httpconfig.filters.add(new hostauthenticationfilter(oauthdefaults.authenticationtype)); httpconfig.formatters.jsonformatter.serializersettings.contractresolver = new camelcasepropertynamescontractresolver(); // web api routes httpconfig.maphttpattributeroutes(); httpconfig.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); return httpconfig; }
since have access token in owin cookie, want add authorization header before reaches api , successful authentication.
here tried
public class customauthorizeattribute : authorizeattribute { protected override bool isauthorized(system.web.http.controllers.httpactioncontext actioncontext) { var cookies = actioncontext.request.headers.getcookies(".aspnet.cookies"); var cookie = cookies.first().cookies.firstordefault(c => c.name == ".aspnet.cookies"); if (cookie != null) { var unprotectedticket = startup.oauthoptions.ticketdataformat.unprotect(ticket); actioncontext.request.headers.add("authorization", string.format("bearer {0}", unprotectedticket.identity.claims.first(c => c.type == "access_token").value)); } return base.isauthorized(actioncontext); } }
i try owin middleware placed after app.usewebapi(configureapi());
public class usecookietobearerauthentication : owinmiddleware { public usecookietobearerauthentication(owinmiddleware next) : base(next) { } public async override task invoke(iowincontext context) { //todo retrieve cookie name somewhere in formsauthentication.formscookiename var cookies = context.request.cookies; var cookie = cookies.firstordefault(c => c.key == ".aspnet.cookies"); if (!cookie.equals(default(keyvaluepair<string, string>))) { var ticket = cookie.value; var unprotectedticket = startup.oauthoptions.ticketdataformat.unprotect(ticket); context.request.headers.add("authorization", new string[]{ string.format("bearer {0}", unprotectedticket.identity.claims.first(c => c.type == "access_token").value) }); } await next.invoke(context); } }
so, how can achieve token authentication web api based on access token in owin cookie?.
thanks in advance.
the problem identityserverbearertokenauthenticationoptions default uses authenticationmode = validationmode.validationendpoint;
default uses microsoft.owin.security.authenticationmode.active
, cannot overriden.
so set identityserverbearertokenauthenticationoptions validationmode = validationmode.local;
, authenticationmode = microsoft.owin.security.authenticationmode.passive;
fine because access token jwt (self-contained).
i use owin middleware access token cookie on request , set on autorization header.
public class usecookietobearerauthentication : owinmiddleware { public usecookietobearerauthentication(owinmiddleware next) : base(next) { } public async override task invoke(iowincontext context) { var x = startup.oauthoptions.cookiename; var cookiename = string.format("{0}{1}", cookieauthenticationdefaults.cookieprefix, cookieauthenticationdefaults.authenticationtype); var cookies = context.request.cookies; var cookie = cookies.firstordefault(c => c.key == ".aspnet.cookies"); if (!cookie.equals(default(keyvaluepair<string, string>))) { var ticket = cookie.value; var unprotectedticket = startup.oauthoptions.ticketdataformat.unprotect(ticket); context.request.headers.add("authorization", new string[]{ string.format("bearer {0}", unprotectedticket.identity.claims.first(c => c.type == "access_token").value) }); } await next.invoke(context); } }
Comments
Post a Comment