How can I overwrite Login Url in ServiceStack.MVC

2019-06-07 07:01发布

问题:

How can I override login Url?

Could you add it to AuthenticateAttribute as property?

回答1:

When using ServiceStacks' authentication mechanism you inherit from either ServiceStackController or ServiceStackController<T> which in turn inherits the former.

The login URL is dictated by the LoginRedirectUrl property of ServiceStackController.

public virtual string LoginRedirectUrl
{
    get { return "/login?redirect={0}"; }
}

Since it is virtual you can simply override it in your own Controller. Or even better, make your own abstract base controller that inherits from ServiceStackController. Then let all your controllers inherit that one. You now have a single point where you control things like the login URL.

public abstract class MyControllerBase : ServiceStackController
{
    public override string LoginRedirectUrl
    {
        get { return "/letslogin?redirectTo={0}"; }
    }
}


回答2:

Not sure if it's new, but looked at the code and it is actually just optional third parameter of AuthFeature constructor, so you can just:

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


回答3:

In the System.Web.Security.FormsAuthentication namespace:

FormsAuthentication.LoginUrl

If you want to override the Web.config value, just implement your own authorize attribute:

[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);
        }
    }
}