In Asp.net mvc, we just need to mark a [authorization] on the “Action” or “Controller” required to be authenticated during authentication. When the users did not login in ,it will return the result “ActionResult is 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;
}
}
From the source code of HttpUnauthorizedResult ,we can get to know that it is very easy or simple to execute HttpUnauthorizedResult .We just set the current HttpContext.Response of the status code as “401”,which will activate authentication module to execute unauthorized handler by default .In other words , It will jump to the logging page ,but the address of the default ReturnURL parameter is relative ,which obviously can’t meet my needs when implementing SSO under different domains .
The resolution is to inherit the feature AuthorizeAttribute and rewrite the OnAuthorization method.
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)));
}
}
}
It is just ok when we used the method we just mark the self-defining ClientAuthorizeAttribute on “Action” or “Controller” which are required to be authenticated .For example:
[HandleError]
[ClientAuthorize(Roles = "Admin")]
public class AdminController : Controller
{
//
// GET: /Admin/
public ActionResult Index()
{
return View();
}
}