本文介绍了ServiceStack认证失败时,不重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在构建一个将使用基本身份验证的 ServiceStack API.我目前在我的 AppHost 中设置了身份验证,如下所示:

We're building a ServiceStack API which will use Basic authentication. I've currently set up the auth in my AppHost as follows:

var authDb = new OrmLiteConnectionFactory("Server=(...);", true, MySqlDialectProvider.Instance);

var authRepo = new OrmLiteAuthRepository(authDb);
authRepo.CreateMissingTables();
container.Register<ICacheClient>(c => new MemoryCacheClient());
container.Register<IUserAuthRepository>(c => authRepo);

Plugins.Add(
    new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() })
);

当执行没有授权标头或错误的用户名+传递的请求时,响应是重定向到/Account/Login.aspx?ReturnUrl=...

When doing a request with no Authorization header or the wrong username+pass the response is a redirect to /Account/Login.aspx?ReturnUrl=...

部分请求 + 响应示例:

Parital request + response example:

POST http://localhost:60278/reserve HTTP/1.1

HTTP/1.1 302 Found
Location: /Account/Login.aspx?ReturnUrl=%2freserve
X-Powered-By: ServiceStack/3,924 Win32NT/.NET

有没有办法让它只响应 HTTP 401 Unauthorized 或 HTTP 403 Forbidden ?

Is there a way to make it respond with only a HTTP 401 Unauthorized or a HTTP 403 Forbidden ?

推荐答案

默认情况下,ServiceStack 的 AuthFeature 只会尝试将您重定向到 HTML 的默认 ~/login 路径内容类型请求.您可以通过将 AuthFeature 中的重定向路径设置为 null 来覆盖它:

By default ServiceStack's AuthFeature will only try to redirect you to the default ~/login path for HTML Content-Type requests. You can override this by setting the redirect path in the AuthFeature to null:

Plugins.Add(new AuthFeature(...) { HtmlRedirect = null });

这将回退到其他 Content-Type 获得的标准 401 UnAuthorized 响应.

This will fall back to the standard 401 UnAuthorized Response that the other Content-Types get.

将 HtmlRedirect 全局设置为 null 后,您可以临时添加它,例如:

After globally setting the HtmlRedirect to null, you can add it back on an adhoc basis, e.g:

[Authenticate(HtmlRedirect="~/path/to/redirect/to")]

这篇关于ServiceStack认证失败时,不重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:34