401 error when using [Authenticate] with BasicAuth

2019-05-14 08:43发布

I'm having some trouble with authenticating with ServiceStack using the BasicAuthProvider. All works well when I authenticate using the provider route 'auth/myauth' but when I go to one of my other service DTOS that use the [Authenticate] attribute e.g. /hello, I always get a 401 Unauthorized error even when I always supply the basic authentication details in the 'Authorization' header using beforeSend with jQuery.

Basically, I'm building an API for a mobile app that involves credential authentication on the first time(or if a supplied token isn't expired), then subsequently basic authentication of supplied token for other requests. I'm trying to authenticate every request, as described here. Also here. Here's my code:

Custom Provider

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;
    }
}

Service

    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 };
    }
} 

Configure Method

    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" }
        },
    });
}

This works

    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);
  }
});

But this doesn't

$.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);
  }
});

Thanks for your help.

1条回答
Explosion°爆炸
2楼-- · 2019-05-14 09:22

I had to create a custom authenticate attribute with guidance from this gist -> https://gist.github.com/joeriks/4518393

In the AuthenticateIfBasicAuth method, I set provider to use MyAuthProvider.Name

Then,

[CustomAuthenticate]
public object Post(Hello request)
{
   return new HelloResponse { Result = "Hello, " + request.Name };
}
查看更多
登录 后发表回答