How can I overwrite Login Url in ServiceStack.MVC authentication?

此生再无相见时 提交于 2019-12-23 04:19:09

问题


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


来源:https://stackoverflow.com/questions/11301790/how-can-i-overwrite-login-url-in-servicestack-mvc-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!