我有一个服务堆栈REST-API,我想从客户端访问。我使用自定义CredentialsAuthProvider实现了授权机制。
这是我的CustomCredentialsAuthProvider。我让这个例子尽可能简单。
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (userName == "admin" && password == "test")
return true;
return false;
}
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
try
{
base.OnAuthenticated(authService, session, tokens, authInfo);
// Save the browser cookie.
if (authService.Request is IHttpResponse httpRes)
httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
// Save the user session object (ServiceStack stores it in the in-memory cache).
authService.SaveSession(session, this.SessionExpiry);
return new HttpResult(HttpStatusCode.Accepted);
}
catch (Exception ex)
{
return new HttpResult(HttpStatusCode.ExpectationFailed);
}
}
现在查看ServiceStack文档:http://docs.servicestack.net/authentication-and-authorization#authenticating-with-http
它说
使用CustomCredentialsAuthProvider进行身份验证(其中 继承自CredentialsAuthProvider)你会POST:
POST localhost:60339 / auth / credentials?format = json
{
"UserName": "admin",
"Password": "test",
"RememberMe": true }
}
可悲的是,我不知道在我的客户端使用什么功能来做这样的POST请求。
这是我的客户。但这并不起作用。
using (var client = new JsonServiceClient("http://localhost:24131"))
{
client.AddHeader("Username", "admin");
client.AddHeader("Password", "test");
client.Post<HttpWebResponse>("/auth/credentials?format=json");
response = client.Get(new GetProducts());
}
有人可以给我一个简单的代码示例,说明如何从我的客户端对CustomCredentialsAuthProvider进行身份验证吗?
由于
答案 0 :(得分:2)
您通常会使用键入的Authenticate
DTO,例如:
var client = new JsonServiceClient(baseUrl);
client.Post(new Authenticate {
provider = “credentials”,
Username = “admin”,
Password = “test”,
RememberMe = true
});
请注意,您不需要处理NO OP。
的JsonServiceClient