3

我在使用 BasicAuthProvider 对 ServiceStack 进行身份验证时遇到了一些问题。当我使用提供程序路由“auth/myauth”进行身份验证时,一切正常,但是当我转到使用 [Authenticate] 属性(例如 /hello)的其他服务 DTOS 时,即使我总是提供 401 Unauthorized 错误,我总是会收到'Authorization' 标头中使用 beforeSend 和 jQuery 的基本身份验证详细信息。

基本上,我正在为移动应用程序构建一个 API,该 API 第一次涉及凭据身份验证(或者如果提供的令牌未过期),然后对其他请求提供的令牌进行基本身份验证。我正在尝试验证每个请求,如此所述。也在这里。这是我的代码:

自定义提供程序

public class MyAuthProvider : BasicAuthProvider
{
    public new static string Name = "MyAuth";
    public new static string Realm = "/auth/myauth";

    public MyAuthProvider()
    {
        this.Provider = Name;
        this.AuthRealm = Realm;
    }

    public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
    {
        var httpReq = authService.RequestContext.Get<IHttpRequest>();
        var basicAuth = httpReq.GetBasicAuthUserAndPassword();

        if (basicAuth == null)
            throw HttpError.Unauthorized("Invalid BasicAuth credentials");

        var us = basicAuth.Value.Key;
        var ps = basicAuth.Value.Value;

        if (ps == "password")
        {
            return true;
        }

        return false;
    }
}

服务

    public class HelloService : Service
{
    //handle OPTIONS in preflight - http://joeriks.com/2013/01/12/cors-basicauth-on-servicestack-with-custom-authentication/
    public object Options(Hello request) { return true; }

    [Authenticate("MyAuth")]
    public object Post(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }

    [Authenticate("MyAuth")]
    public object Get(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
} 

配置方法

    public override void Configure(Container container)
{
    Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
        new MyAuthProvider()
    }));

    //register any dependencies your services use, e.g:
    container.Register<ICacheClient>(new MemoryCacheClient() { FlushOnDispose = false });

    //set endpoint information
    SetConfig(new EndpointHostConfig
    {
        GlobalResponseHeaders =
        {
            {"Access-Control-Allow-Origin","http://localhost"},
            {"Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"},
            {"Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, Origin" }
        },
    });
}

这有效

    function make_base_auth(user, password) {
 var tok = user + ':' + password;
 var hash = btoa(tok);
 return "Basic " + hash;
}

////

$.ajax({
    url: 'http://localhost:61750/auth/myauth?format=json',
    type: 'POST',
    beforeSend: function(xhr) {
         xhr.setRequestHeader("Authorization", make_base_auth("id@email.com","password"));
    }
    }).done(function (data) {
  if( console && console.log ) {
    console.log("Sample of data:", data);
  }
});

但这并不

$.ajax({
    url: 'http://localhost:61750/hello?format=json',
    data: { Name:"Foo" },
    type: 'POST',
    beforeSend: function(xhr) {
         xhr.setRequestHeader("Authorization", make_base_auth("id@email","password"));
    }
    }).done(function (data) {
  if( console && console.log ) {
    console.log("Sample of data:", data);
  }
});

谢谢你的帮助。

4

1 回答 1

1

我必须在这个 gist 的指导下创建一个自定义的身份验证属性 - > https://gist.github.com/joeriks/4518393

AuthenticateIfBasicAuth方法中,我设置提供者使用MyAuthProvider.Name

然后,

[CustomAuthenticate]
public object Post(Hello request)
{
   return new HelloResponse { Result = "Hello, " + request.Name };
}
于 2013-07-14T21:10:09.170 回答