Question

I am trying to write my own authentication, so I inherited CredentialsAuthProvider and have overridden the Authenticate method. Auth is working fine, also when i call another service i can see all data that i saved in the session.

The Problem is: When i try add the Authenticate attribute and call it from a client, it goes and throws an Unauthorized exception, even if i want to use Requered Role.

Auth service is:

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 is:

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


}

and test service:

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

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

It is not real code, so sorry for syntax mistake!)))) But the idea is the same! Help me please what is wrong, why I got Unauthorized exception when i call Test service??????????

Was it helpful?

Solution

When I had this issue, I had to create a custom authenticate attribute [CustomAuthenticate] with guidance from this gist -> https://gist.github.com/joeriks/4518393

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

Then,

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top