How to do token based auth using ServiceStack

泪湿孤枕 提交于 2019-11-29 22:35:40

问题


How would I implement the following scenario using ServiceStack?

Initial request goes to http://localhost/auth having an Authorization header defined like this:

Authorization: Basic skdjflsdkfj=

The IAuthProvider implementation validates against a user store and returns a session token as a response body (JSON).

The client uses this token an resends it against the subsequent requests like http://localhost/json/reply/orders using the Authorization header like this:

Authorization: BasicToken <TokenFromPreviousSuccessfulLogin>

Using a AuthenticateAttribute I want to flag my Service to use Authentication.

How should I implement the validation of the token for the subsequent requests? How should I implement the IAuthProvider to provide the token? How would I register the Providers etc.? Using RequestFilters or using the AuthFeature?


回答1:


ServiceStack's JWT AuthProvider and API Key AuthProvider both use token based Authentication.

Otherwise the BasicAuth Provider is a very simple class that simply extracts the UserName and Password from the BasicAuth Header and evaluates it:

public override object Authenticate(...)
{
    var httpReq = authService.RequestContext.Get<IHttpRequest>();
    var basicAuth = httpReq.GetBasicAuthUserAndPassword();
    if (basicAuth == null)
        throw HttpError.Unauthorized("Invalid BasicAuth credentials");

    var userName = basicAuth.Value.Key;
    var password = basicAuth.Value.Value;

    return Authenticate(authService, session, userName, password, request.Continue);
}

If you want to provide enhanced behavior, I would simply inherit this class check for the Authorization: BasicToken header, if it exists use that otherwise call the base.Authenticate(...) method to perform the initial validation.



来源:https://stackoverflow.com/questions/16673988/how-to-do-token-based-auth-using-servicestack

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