如果未经过身份验证,则重定向到Login

本文关键字:重定向 Login 经过 身份验证 如果 | 更新日期: 2023-09-27 18:02:42

我有一个在一个域中具有多个模块的应用程序。https://SomeDomain.es/

假设我有模块module1和module2,我可以访问模块
https://SomeDomain.es/module1

https://SomeDomain.es/module2

当我尝试访问上面的url,它重定向到登录页面,如果没有认证。如果我试图访问module1内的页面,那么它不会重定向到登录页面。相反,它试图通过初始化控制器来提供响应。控制器有一个需要ICustomPrincipal作为参数的构造函数,它是使用Unity IOC注入的。解析ICustomPrincipal时失败,因为Identity为空。

https://SomeDomain.es/module1(重定向到登录)

https://SomeDomain.es/module1/Profile/2(不重定向到login)

网络。配置:

 <authentication mode="Forms">
   <forms name=".SomeLoginCookie" loginUrl="~/Account/Login" timeout="2880" protection="All" enableCrossAppRedirects="true" />
 </authentication>

我使用自定义授权属性,标记在控制器

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public ICustomPrincipal customPrincipal;
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorize = false;
        authorize = base.AuthorizeCore(httpContext);
        if(!authorize)
            return false;
        if(!httpContext.Request.IsAuthenticated)
            return false;
        if(customPrincipal== null)
        {
            var factory = new PrincipalFactory(httpContext.User);
            customPrincipal= factory.CreatePrincipal();
        }
        if(customPrincipal.HasPermissions(function))
            authorize = true;
        else
            authorize = false;
        return authorize;
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(filterContext.HttpContext.Request != null && filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new ViewResult() { ViewName = "AccessDenied" };
                //new HttpStatusCodeResult(403);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }

我已经测试了使用[Authorize]属性代替自定义属性,但没有成功。

我不知道这里有什么问题。请分享你的想法。

控制器:

[NoCache]
[CustomAuthorize(CustomFunction.Profile)]
public partial class ProfileController : Controller
{
    public ICustomPrincipal Principal {get; set;}
    public ProfileController(ICustomPrincipal principal)
    {
        Principal = principal;
    }
    public ActionResult Index(int Id)
    {
    }
}

超时时也是如此

如果未经过身份验证,则重定向到Login

当我使用表单身份验证时,我使用以下方法设置身份验证cookie:

FormsAuthentication.SetAuthCookie