如何在没有ServiceStack用户会话的情况下启用基本身份验证?

时间:2014-08-10 11:54:24

标签: servicestack basic-authentication

根据ServiceStack github wiki为了在ServiceStack中添加/启用基本身份验证,需要以下代码行:

Plugins.Add(new AuthFeature(() => new AuthUserSession(),
      new IAuthProvider[] { 
        new BasicAuthProvider(), //Sign-in with Basic Auth
        new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
      }));

但是如何在没有用户会话的情况下添加基本身份验证?

1 个答案:

答案 0 :(得分:2)

如果要在不使用会话的情况下执行身份验证,则可以创建一个简单的请求筛选器,自行执行基本身份验证。

然后,您可以针对您自己的数据库或存储库对凭据进行身份验证,或者您可以针对下面显示的标准ServiceStack存储库进行身份验证

public class MyAuthenticateAttribute : RequestFilterAttribute
{
    public override void Execute(IRequest req, IResponse res, object requestDto)
    {
        // Determine if request has basic authentication
        var authorization = req.GetHeader(HttpHeaders.Authorization);

        if(!String.IsNullOrEmpty(authorization) && authorization.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        {
            // Decode the credentials
            var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authorization.Substring(6))).Split(':');
            if(credentials.Length == 2)
            {
                // Perform authentication checks. You could do so against your own database
                // or you may wish to use the ServiceStack authentication repository IUserAuthRepository

                // If you want to check against ServiceStacks authentication repository
                var repository = HostContext.TryResolve<IUserAuthRepository>();
                if(repository == null)
                    throw new Exception("Authentication Repository is not configured");

                // Try authenticate the credentials
                IUserAuth user;
                if(repository.TryAuthenticate(credentials[0], credentials[1], out user))
                {
                    // Authenticated successfully

                    // If you need the user details available in your service method
                    // you can set an item on the request and access it again in your service
                    // i.e. req.SetItem("user", user);
                    // In your service: Request.GetItem("user") as IUserAuth

                    return;
                }
            }
        }

        // User requires to authenticate
        res.StatusCode = (int)HttpStatusCode.Unauthorized;
        res.AddHeader(HttpHeaders.WwwAuthenticate, "basic realm=\"My Secure Service\"");
        res.EndRequest();
    }
}

因此,您不会使用[Authenticate]属性,而是使用[MyAuthenticate]属性。

AppHost Configure方法中,请勿添加AuthFeature插件。但是,您仍然需要添加存储库,如果这是您选择对凭据进行身份验证的方式。

container.Register<ICacheClient>(new MemoryCacheClient());
var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);

我希望这会有所帮助。

相关问题