これが私のシナリオです。Thinktecture.IdentityServerプロバイダーに基づくOpenIdConnectAuthenticationを使用する MVC4.5/WebApi2 アプリケーションがあります。これまでのところ、MVC に対して認証できます。ここで、Bearer Token を使用して WebApi に対して認証したいと考えています。これが私の構成です
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
}
};
);
そして私のWebApi構成
public HttpConfiguration ConfigureAPI() {
var httpConfig = new HttpConfiguration();
// Configure Web API to use only 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;
}
OWIN Cookie に既にアクセス トークンがあるため、API に到達する前にそれを認証ヘッダーに追加して、認証を成功させたいと考えています。
これが私が試したものです
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);
}
}
後に配置されたOWINミドルウェアでも試してみますapp.UseWebApi(ConfigureAPI());
public class UseCookieToBearerAuthentication : OwinMiddleware {
public UseCookieToBearerAuthentication(OwinMiddleware next) : base(next) { }
public async override Task Invoke(IOwinContext context) {
//TODO Retrieve cookie name from somewhere like 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);
}
}
では、Owin Cookie のアクセス トークンに基づいて Web API のトークン認証を行うにはどうすればよいでしょうか。
前もって感謝します。