在asp.net mvc进行身份验证只用在需要验证的Action或者Controller上标记一个[authorization]即可,如果用户没有登陆,此时将返回的ActionResult是HttpUnauthorizedResult
public class HttpUnauthorizedResult : ActionResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
// 401 is the HTTP status code for unauthorized access - setting this
// will cause the active authentication module to execute its default
// unauthorized handler
context.HttpContext.Response.StatusCode = 401;
}
}
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
// 401 is the HTTP status code for unauthorized access - setting this
// will cause the active authentication module to execute its default
// unauthorized handler
context.HttpContext.Response.StatusCode = 401;
}
}
从HttpUnauthorizedResult的源码可以看出,HttpUnauthorizedResult的执行很简单,就是设置当前的HttpContext.Response的状态码为401,这样就回激活authentication module 执行它默认的 unauthorized handler,也就是跳转到登陆页面的,但是默认的跳转ReturnURL 参数的地址是相对的,这在不同域名下实现单点登录时显然是不能满足我的需要的。
解决的办法就是继承AuthorizeAttribute这个特性,重写OnAuthorization方法
public class ClientAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult(
string.Concat(FormsAuthentication.LoginUrl,
"?ReturnUrl=",
filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri)));
}
}
}
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult(
string.Concat(FormsAuthentication.LoginUrl,
"?ReturnUrl=",
filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri)));
}
}
}
使用的时候在需要身份验证的Action或者Controller上标记上我们自定义的这个ClientAuthorizeAttribute就行了。
例如:
[HandleError]
[ClientAuthorize(Roles = "Admin")]
public class AdminController : Controller
{
//
// GET: /Admin/
public ActionResult Index()
{
return View();
}
}
[ClientAuthorize(Roles = "Admin")]
public class AdminController : Controller
{
//
// GET: /Admin/
public ActionResult Index()
{
return View();
}
}