从ServiceStack身份验证返回自定义身份验证响应对象

时间:2013-04-29 13:47:35

标签: servicestack

是否可以返回自定义身份验证响应?我已经拥有自己的自定义身份验证提供程序,它继承自CredentialsAuthProvider。

我想在响应中返回会话到期日期,以便客户端确切地知道他们的服务器会话何时到期:

{
    "sessionId": "bG27SdxbRkqJqU6xv/gvBw==",
    "userName": "joe.bloggs@letmein.com",
    "sessionExpires": "2013-04-29T03:27:14.0000000",
    "responseStatus": {}
}

我可以像这样覆盖Authenticate方法:

public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
{
    // get base response
    var response = base.Authenticate(authService, session, request);

    // grab the session
    var customSession = authService.GetSession() as CustomUserSession;

    // if response can be cast and customSession exists
    if (response is AuthResponse && customSession != null)
    {
        // cast
        var authResponse = response as AuthResponse;

        // build custom response
        var customAuthResponse = new CustomAuthResponse
            {
                ReferrerUrl = authResponse.ReferrerUrl,
                SessionExpiry = customSession.SessionExpires,
                SessionId = authResponse.SessionId,
                ResponseStatus = authResponse.ResponseStatus,
                UserName = authResponse.UserName
            };
        return customAuthResponse;
    }

    // return the standard response
    return response;
}

这种方法很好,除非会话已经处于活动状态。在这种情况下,AuthService Post方法检查有效会话和automatically returns a standard AuthResponse,并且没有明显的方法来覆盖它:

var alreadyAuthenticated = response == null;
response = response ?? new AuthResponse {
    UserName = session.UserAuthName,
    SessionId = session.Id,
    ReferrerUrl = referrerUrl,
};

根据下面的Paaschpa的想法,以下强制重新认证总是被重新认证,但似乎可能存在使多个活动会话保持打开的风险:

public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null)
{
    // force re-authentication. Not great, but no other obvious way to do this
    if (request != null)
    {
        return false; // auth or re-auth calls
    }

    return base.IsAuthorized(session, tokens, request);
}

有人能想到更好的方法吗?我可以实现自己的AuthenticationService,但我不确定如何覆盖AuthFeature?

1 个答案:

答案 0 :(得分:4)

如果我理解正确,您希望在用户对'/auth/credentials'进行身份验证后返回自定义响应。由于您已拥有自己的CredentialsAuthProvider,我认为您可以覆盖身份验证并返回自己的回复。

CredentialsAuthProvider的子类

public class MyCredentialsAuthProvider : CredentialsAuthProvider
{
    public override object Authenticate(ServiceStack.ServiceInterface.IServiceBase authService, IAuthSession session, Auth request)
    {
        //let normal authentication happen
        var authResponse = (AuthResponse)base.Authenticate(authService, session, request);

        //return your own class, but take neccessary data from AuthResponse
        return new
            {
                UserName = authResponse.UserName,
                SessionId = authResponse.SessionId,
                ReferrerUrl = authResponse.ReferrerUrl,
                SessionExpires = DateTime.Now
            };

    }
}