2016-07-29 93 views
0

我想讓服務堆服務只有授權用戶纔可訪問。這是我的註冊方法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;未經授權的例外,ServiceStack

這是登錄方法

[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

看一看在ServiceStack MVC documentation爲例如何從MVC使用ServiceStack認證,如而是採用了ServiceClient你可以調用ServiceStack的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到將對您的服務的訪問權限限制爲經過身份驗證的客戶

+0

感謝您的幫助。當我重定向到另一個動作時,它仍會引發未經授權的異常,我是否必須在每個控制器中進行身份驗證? –

+0

@MartynasBrazionis你只需要驗證一次,然後你就可以調用受ServiceStack的'[Authenticate]'屬性保護的控制器,如http://mvc.servicestack.net演示中所示。注意你的控制器應該繼承'ServiceStackController'。 – mythz

相關問題