未经授权的异常,ServiceStack

时间:2016-07-29 14:09:58

标签: asp.net-mvc authorization servicestack unauthorized

我想只为授权用户提供服务堆栈服务。这是我的注册方法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;

这是登录方法

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

尽管我在登录方法中验证用户,但为什么会发生此异常?我是否必须在AppHost中更改一些代码?感谢。

1 个答案:

答案 0 :(得分:1)

查看ServiceStack MVC documentation有关如何从MVC使用ServiceStack身份验证的示例,例如,不要使用ServiceClient,而是直接调用ServiceStack&#39; s AuthenticateService

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

然后,您可以使用ServiceStack的Authentication Attributes来限制对经过身份验证的客户端的服务访问。