2012-12-13 28 views
3

默認情況下,當我嘗試在授權之前調用任何內容時,ServiceStack會返回http狀態401。 如何返回http狀態200和我的DTO而不是?如何更改ServiceStack中的HTTP 401響應?

理想情況下,我想在ResponseStatus應用程序範圍內顯示布爾值NeedAuth = true標誌,如果我嘗試調用任何未經授權的東西。

回答

0

我修改了我之前創建的自定義AuthProvider。現在 如果我叫什麼身份驗證之前或試圖提供錯誤的憑據,我得到HTTP 200個OK狀態和這種反應:

{ 
    "NeedAuth": true 
} 

我已經擴展AuthResponse:

public class MyAuthResponse : AuthResponse 
{ 
    public bool? NeedAuth { get; set; } 
} 

而且修改了我的自定義AuthProvider繼承自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; 
} 
1

將401寫入響應,目前沒有辦法撤消該操作。如果您有特殊要求,則不需要使用內置的身份驗證功能。

只需創建您自己的請求過濾器,它就是您想要的內容,這就是內置Auth的工作原理,它只是一個請求過濾器。

+0

你能更具體一點,我應該改變什麼以及在哪裏改寫默認的Auth行爲?什麼是覆蓋內置功能的最簡潔的方法? – Savvkin

+0

我的意思是不啓用ServiceStack的身份驗證,只提供自己的。 SS認證提供商從ServiceStack分離出來,只是使用請求過濾器創建,你可以輕鬆地做到這一點。 – mythz