我要求让我的启用身份的MVC网站使用WebApi使用cookie进行网站和网络API的身份验证。处理此问题的任何人都可能知道这可能容易受到XSS攻击,因为可以通过访问恶意页面将常规登录cookie发送到您的webapi方法。
将cookie与web api一起使用的奇怪要求是问题的根源。有没有办法安全地做到这一点?
我在AuthorizationFilter
(下面发布)中使用表单身份验证有一个解决方案,但我希望利用身份框架的功能,例如声明和注销到处。
using System;
using System.Web.Http.Filters;
using System.Web.Http;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Collections.Generic;
namespace Filters
{
/// <summary>
/// An authentication filter that uses forms authentication cookies.
/// </summary>
/// <remarks>Use the *Cookie static methods to manipulate the cookie on the client</remarks>
public class FormsAuthenticationFilter : Attribute, IAuthenticationFilter
{
public static long Timeout { get; set; }
public static string CookieName { get; set; }
public FormsAuthenticationFilter()
{
// Default Values
FormsAuthenticationFilter.Timeout = FormsAuthentication.Timeout.Minutes;
FormsAuthenticationFilter.CookieName = "WebApi";
}
public FormsAuthenticationFilter(long Timeout, string CookieName)
{
FormsAuthenticationFilter.Timeout = Timeout;
FormsAuthenticationFilter.CookieName = CookieName;
}
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
HttpRequestMessage request = context.Request;
// Get cookie
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthenticationFilter.CookieName];
//If no cookie then do nothing
if (cookie == null)
{
return Task.FromResult(0);
}
//If empty cookie then raise error
if (String.IsNullOrEmpty(cookie.Value))
{
context.ErrorResult = new AuthenticationFailureResult("Empty ticket", request);
return Task.FromResult(0);
}
//Decrypt ticket
FormsAuthenticationTicket authTicket = default(FormsAuthenticationTicket);
try
{
authTicket = FormsAuthentication.Decrypt(cookie.Value);
}
catch (Exception)
{
context.ErrorResult = new AuthenticationFailureResult("Invalid ticket", request);
return Task.FromResult(0);
}
//Check if expired
if (authTicket.Expired)
{
context.ErrorResult = new AuthenticationFailureResult("Ticket expired", request);
return Task.FromResult(0);
}
//If caching roles in userData field then extract
string[] roles = authTicket.UserData.Split(new char[] { '|' });
// Create the IIdentity instance
IIdentity id = new FormsIdentity(authTicket);
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, roles);
// Set the context user
context.Principal = principal;
// Update ticket if needed (sliding window expiration)
if ((authTicket.Expiration - DateTime.Now).TotalMinutes < (FormsAuthenticationFilter.Timeout / 2))
{
RenewCookie(authTicket);
}
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
//Do nothing
return Task.FromResult(0);
}
public bool AllowMultiple
{
get { return false; }
}
/// <summary>
/// Renews the cookie on the client using the specified FormsAuthenticationTicket
/// </summary>
/// <param name="OldTicket">A still-valid but aging FormsAuthenticationTicket that should be renewed</param>
/// <remarks></remarks>
protected static void RenewCookie(FormsAuthenticationTicket OldTicket)
{
HttpContext.Current.Response.Cookies.Add(GetCookie(OldTicket.Name, OldTicket.UserData));
}
/// <summary>
/// Sets the authentication cookie on the client
/// </summary>
/// <param name="UserName">The username to set the cookie for</param>
/// <remarks></remarks>
public static void SetCookie(String user, IList<string> roles)
{
HttpContext.Current.Response.Cookies.Add(GetCookie(user, string.Join("|", roles)));
}
/// <summary>
/// Removes the authentication cookie on the client
/// </summary>
/// <remarks>Cookie is removed by setting the expires property to in the past, may not work on all clients</remarks>
public static void RemoveCookie()
{
if ((HttpContext.Current.Response.Cookies[FormsAuthenticationFilter.CookieName] != null))
{
HttpContext.Current.Response.Cookies[FormsAuthenticationFilter.CookieName].Expires = DateTime.Now.AddDays(-1);
}
}
private static HttpCookie GetCookie(string UserName, string UserData)
{
//Create forms auth ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthenticationFilter.Timeout), false, UserData);
//Create cookie with encrypted contents
HttpCookie cookie = new HttpCookie(FormsAuthenticationFilter.CookieName, FormsAuthentication.Encrypt(ticket));
cookie.Expires = DateTime.Now.AddMinutes(FormsAuthenticationFilter.Timeout);
//Return it
return cookie;
}
protected class AuthenticationFailureResult : IHttpActionResult
{
public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
{
this.ReasonPhrase = reasonPhrase;
this.Request = request;
}
public string ReasonPhrase { get; set; }
public HttpRequestMessage Request { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
private HttpResponseMessage Execute()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
response.ReasonPhrase = ReasonPhrase;
return response;
}
}
}
}
答案 0 :(得分:0)
让我先说明这个答案,如果 WebApi方法永远不会通过您网站上的javascript调用,这只是一个解决方案。仅当您计划使用来自其他客户端(如移动应用程序)的WebApi时,才应使用此选项。
解决方案在于为WebApi使用单独的cookie。 WebApi将拒绝正常的站点授权cookie,并仅使用自己的cookie。
在WebApiConfig
类中添加常量和静态方法来配置cookie中间件:
public const string WebApiCookieAuthenticationType = "WebApiCookie";
public static CookieAuthenticationOptions CreateCookieAuthenticationOptions()
{
return new CookieAuthenticationOptions
{
AuthenticationType = WebApiConfig.WebApiCookieAuthenticationType,
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
CookieName = ".AspNet.WebApiCookie",
CookiePath = "/api",
ExpireTimeSpan = TimeSpan.FromDays(14),
SlidingExpiration = true,
LoginPath = new PathString("/api/auth"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(60),
regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, WebApiConfig.WebApiCookieAuthenticationType)
),
OnApplyRedirect = ctx => {}
}
};
}
请注意AuthenticationType
和AuthenticationMode
,这些会阻止我们在注册后干扰正常的网站Cookie。我们接下来会在Startup
课程中执行此操作,将其置于现有app.UseCookieAuthentication()
电话的正下方:
// Setup WebApi Cookie Authentication
app.UseCookieAuthentication(WebApiConfig.CreateCookieAuthenticationOptions());
我们还需要配置WebApi以忽略常规站点cookie并处理我们的特殊cookie。在WebApiConfig.Register()
方法中执行此操作:
// Ignore website auth
config.SuppressHostPrincipal();
config.Filters.Add(new HostAuthenticationFilter(WebApiCookieAuthenticationType));
现在我们正在设置,但您如何发出身份验证Cookie?在您的webapi中创建一个使用标准身份SignInManager
的授权控制器方法,但需要额外的步骤:
[AllowAnonymous]
public async Task<IHttpActionResult> Authenticate(string userName, string password)
{
// Get signIn manager
var signInManager = HttpContext.Current.Request.GetOwinContext().Get<ApplicationSignInManager>();
if (signInManager == null)
{
return BadRequest();
}
// Important!
signInManager.AuthenticationType = WebApiConfig.WebApiCookieAuthenticationType;
// Sign In
var result = await signInManager.PasswordSignInAsync(userName, password, false, shouldLockout: true);
if (result == SignInStatus.Success)
{
// Return
return Ok();
}
// Failure
return BadRequest();
}
要特别注意我们设置SignInManager
的{{1}}的位置,这会使其使用我们特殊的WebApi Cookie而非标准网站Cookie。
一个问题是默认网站模板使用对AuthenticationType
身份验证类型的硬编码引用来覆盖SignInManager
的{{1}}方法。这将干扰此解决方案。要修复它,您可以将覆盖更改为:
CreateUserIdentityAsync
另一个问题是压缩。如果您正在使用优秀的DefaultAuthenticationTypes.ApplicationCookie
软件包,则需要使用public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
if (this.AuthenticationType == DefaultAuthenticationTypes.ApplicationCookie)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
else
{
return base.CreateUserIdentityAsync(user);
}
}
禁用对web api方法的压缩,以便在Identity可以将Set-Cookie标头添加到之前写入响应时进行登录/注销。响应。