如何更改 ServiceStack 中的 HTTP 401 响应? [英] How to change HTTP 401 response in ServiceStack?
问题描述
默认情况下,当我在授权前尝试调用任何内容时,ServiceStack 返回 http 状态 401.我如何返回 http 状态 200 和我的 DTO 而不是那个?
By default, ServiceStack returns http status 401 when I try to call anything before authorization. How do I return http status 200 and my DTO instead of that?
理想情况下,如果我尝试调用任何未经授权的内容,我想在 ResponseStatus 应用程序范围内显示 boolean NeedAuth=true 标志.
Ideally, I want to show boolean NeedAuth=true flag in ResponseStatus application wide, if I try calling anything unauthorized.
推荐答案
我修改了我之前创建的自定义 AuthProvider.现在,如果我在身份验证之前调用任何内容或尝试提供错误的凭据,我会得到 HTTP 200 OK 状态和此响应:
I've modified my previously created custom AuthProvider. Now if I call anything before authentication or try to provide wrong credentials, I get HTTP 200 OK status and this response:
{
"NeedAuth": true
}
我扩展了 AuthResponse:
I've extended AuthResponse:
public class MyAuthResponse : AuthResponse
{
public bool? NeedAuth { get; set; }
}
并修改了我从 CredentialsAuthProvider 继承的自定义 AuthProvider:
And modified my custom AuthProvider inherited from CredentialsAuthProvider:
// This one is called when I call anything before authorization
public override void OnFailedAuthentication(IAuthSession session, ServiceStack.ServiceHost.IHttpRequest httpReq, ServiceStack.ServiceHost.IHttpResponse httpRes)
{
httpRes.StatusCode = (int)HttpStatusCode.OK;
var callback = httpReq.GetJsonpCallback();
var doJsonp = EndpointHost.Config.AllowJsonpRequests && !string.IsNullOrEmpty(callback);
var res = new MyAuthResponse() { NeedAuth = true };
if (doJsonp)
httpRes.WriteToResponse(httpReq, res, (callback + "(").ToUtf8Bytes(), ")".ToUtf8Bytes());
else
httpRes.WriteToResponse(httpReq, res);
}
// This one is called when I try to login
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
{
var userName = request.UserName;
var password = request.Password;
var res = new MyAuthResponse();
if (!LoginMatchesSession(session, userName))
{
authService.RemoveSession();
session = authService.GetSession();
}
if (TryAuthenticate(authService, userName, password))
{
if (session.UserAuthName == null)
session.UserAuthName = userName;
OnAuthenticated(authService, session, null, null);
res.UserName = userName;
res.SessionId = session.Id;
}
else
res.NeedAuth = true;
return res;
}
这篇关于如何更改 ServiceStack 中的 HTTP 401 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!