Martynas B
Martynas B

Reputation: 3143

Unauthorized exception, ServiceStack

I want to make servicestack services reachable only for authorized users. this is my register method var authResponse = client.Post(new Authenticate { provider = CredentialsAuthProvider.Name, //= credentials UserName = model.Username, Password = model.Password, RememberMe = true, }); client.UserName = model.Username; client.Password = model.Password;

This is Log in method

[HttpPost]
    [ActionName("LogIn")]
    public ActionResult Login(LogInModel model)
    {
        var authResponse = client.Post(new Authenticate
        {
            provider = CredentialsAuthProvider.Name, //= credentials
            UserName = model.Username,
            Password = model.Password,
            RememberMe = true,
        });
        client.UserName = model.Username;
        client.Password = model.Password;

        return RedirectToAction("RefundPayment");
    }

Apphost :

   public override void Configure(Container container)
    {
        SetConfig(new HostConfig
        {
            HandlerFactoryPath = "api",
        });
        //Config examples
        //this.Plugins.Add(new PostmanFeature());
        //this.Plugins.Add(new CorsFeature());

        //Set MVC to use the same Funq IOC as ServiceStack
        ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));

        Plugins.Add(new AuthFeature(() => new AuthUserSession(),
          new IAuthProvider[] {
            new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
            new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
          }));

        Plugins.Add(new RegistrationFeature());

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

Why this exception occurs despite I Authenticate user in Log In method? Do I have to change some code in AppHost? Thanks.

Upvotes: 0

Views: 490

Answers (1)

mythz
mythz

Reputation: 143359

Have a look at the ServiceStack MVC documentation for an example on how to use ServiceStack Authentication from MVC, e.g instead of using a ServiceClient you could be calling ServiceStack's AuthenticateService directly:

using (var authService = ResolveService<AuthenticateService>())
{
    var response = authService.Authenticate(new Authenticate {
        provider = CredentialsAuthProvider.Name,
        UserName = userName,
        Password = password,
        RememberMe = true,
    });

    // add ASP.NET auth cookie
    FormsAuthentication.SetAuthCookie(userName, true);

    return Redirect(string.IsNullOrEmpty(redirect) ? "/" : redirect);
}

Then you can use ServiceStack's Authentication Attributes to limit access to your Service to authenticated clients.

Upvotes: 1

Related Questions