ServiceStack,Authenticate属性

时间:2013-07-12 15:29:36

标签: authentication attributes servicestack custom-authentication

我正在尝试编写自己的身份验证,因此我继承了CredentialsAuthProvider并重写了Authenticate方法。 Auth工作正常,当我打电话给另一个服务时,我可以看到我在会话中保存的所有数据。

  

问题是:当我尝试添加Authenticate属性并从客户端调用它时,即使我想使用Requered Role,它也会抛出一个Unauthorized异常。

验证服务是:

public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
    {
        return true;
    }

    public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
    {

        session.FirstName = "Name";
        //...
        session.Authenticate = true;
        session.UserName = request.UserName;
        session.Roles = new List<string>;
        session.Roles.Add("admin")
        //....
        authService.SaveSession(session, SessionExpiry);

        // Return custom object
        return new UserAuthResponse { SessionId = session.Id ......};

    }

AppHost是:

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

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


}

和测试服务:

[Authenticate]
public class TestService : Service { 
    public object Any(UserRequest request) {

       return new UserResponse{Name = request.Name};
    }
}

这不是真正的代码,所以抱歉语法错误!)))) 但这个想法是一样的!请帮我解决有什么问题,为什么我在调用测试服务时遇到了未经授权的异常???????????

1 个答案:

答案 0 :(得分:2)

当我遇到此问题时,我必须在此要点的指导下创建自定义身份验证属性[CustomAuthenticate] - &gt; https://gist.github.com/joeriks/4518393

在AuthenticateIfBasicAuth方法中,我将提供程序设置为使用MyAuthProvider.Name而不是BasicAuthProvider.Name

然后,

[CustomAuthenticate]
public class TestService : Service { 
    public object Any(UserRequest request) {

       return new UserResponse{Name = request.Name};
    }
}

另见:http://joeriks.com/2013/01/12/cors-basicauth-on-servicestack-with-custom-authentication/