如何在ServiceStack.MVC身份验证中覆盖登录URL?

时间:2012-07-02 22:02:34

标签: asp.net-mvc authentication servicestack

如何覆盖登录网址?

您可以将它作为属性添加到AuthenticateAttribute吗?

3 个答案:

答案 0 :(得分:4)

不确定它是否是新的,但是看了一下代码,它实际上只是AuthFeature构造函数的可选第三个参数,所以你可以这样做:

//htmlRedirect is optional 3rd param of AuthFeature constructor, here passing "~/signin"
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(), }, "~/signin"));

答案 1 :(得分:2)

使用ServiceStacks的身份验证机制时,您继承ServiceStackControllerServiceStackController<T>,后者继承前者。

登录网址由LoginRedirectUrl的{​​{1}}属性决定。

ServiceStackController

由于它是虚拟的,您可以在自己的Controller中简单地覆盖它。或者甚至更好,制作自己的继承自public virtual string LoginRedirectUrl { get { return "/login?redirect={0}"; } } 的抽象基础控制器。然后让所有控制器继承那个控制器。您现在有一个单点可以控制登录URL等内容。

ServiceStackController

答案 2 :(得分:0)

在System.Web.Security.FormsAuthentication名称空间中:

FormsAuthentication.LoginUrl

如果要覆盖Web.config值,只需实现自己的authorize属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorize: AuthorizeAttribute{
    public override void OnAuthorization(AuthorizationContext filterContext) {
        //If the request does not provide authentication, then perform a redirect
        if (!filterContext.HttpContext.Request.IsAuthenticated) {
            var loginUrl = FormsAuthentication.LoginUrl; //Change your URL here if needed.

            filterContext.Result = new RedirectResult(loginUrl);
        } else {
            //Since the request was authenticated, perform the default authorization check.
            base.OnAuthorization(filterContext);
        }
    }
}