使用[授权]与BasicAuthProvider时401错误 [英] 401 error when using [Authenticate] with BasicAuthProvider

查看:1142
本文介绍了使用[授权]与BasicAuthProvider时401错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些麻烦,使用BasicAuthProvider与ServiceStack认证。一切运作良好时,我可以验证使用所提供的路线'auth /中myauth但是当我去我的其他服务DTOS之一是使用[授权]属性如/你好,我总是得到一个401错误未经授权即使我总是用beforeSend与jQuery的授权头提供基本身份验证的详细信息。

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.

基本上,我要建一个API,用于移动应用,涉及上首次凭证验证(或者如果提供的令牌没有过期),那么对于其他请求提供的令牌随后基本身份验证。我想每一个请求进行身份验证,所描述的这里。此外<一个href=\"http://stackoverflow.com/questions/16673988/how-to-do-token-based-auth-using-servicestack\">here.这里是我的code:

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:

自定义提供商

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

感谢您的帮助。

推荐答案

我不得不从这个要点创建指导定制的身份验证属性 - >的 https://gist.github.com/joeriks/4518393

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

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

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

然后,

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

这篇关于使用[授权]与BasicAuthProvider时401错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆