英文:
Passing credentials for authentication to C# ASP.NET Web API
问题
我已经设置了一个ASP.NET Web API。我想要动态验证提供的基本身份验证(用户名和Web访问密钥),并将其传递给我设置的网络凭据方法来验证详细信息。
这是我的模型:
public class Customer
{
public string No_;
public string Name;
public string AccountingLocation;
}
我的控制器:
public IHttpActionResult Get(string id)
{
try
{
ws.ValidationRegWebService();
Validation.Customer customerVal = new Validation.Customer();
customerVal = ws.validationReg_ws.Read(id);
[...]
}
[...]
}
我的网络凭据方法:
public NetworkCredential Credential()
{
NetworkCredential cred = new NetworkCredential
{
UserName = globals.UserName,
Password = globals.Password
};
return cred;
}
如何将客户端的授权详细信息传递给网络凭据方法?
英文:
I have setup an ASP.NET Web API. I want to dynamically validate the basic authentication provided (username and web access key) in the header and pass it to the network credentials method I have setup to validate details.
This is my model:
public class Customer
{
public string No_;
public string Name;
public string AccountingLocation;
}
My controller:
public IHttpActionResult Get(string id)
{
try
{
ws.ValidationRegWebService();
Validation.Customer customerVal = new Validation.Customer();
customerVal = ws.validationReg_ws.Read(id);
[...]
}
[...]
}
My network credential method:
public NetworkCredential Credential()
{
NetworkCredential cred = new NetworkCredential
{
UserName = globals.UserName,
Password = globals.Password
};
return cred;
}
How can I pass the authorization details from the client to the network credential method?
答案1
得分: 1
在该方法中,您可以像这样获取Postman发送的基本身份验证头:
var header = Request.Headers["Authorization"].FirstOrDefault();
if (header == null) throw UnauthorizedException(); // 不确定这个异常是否存在,我只是编造的
然后解码它,因为它只是包含以base64编码的用户名:密码,并以"Basic "为前缀:
var encodedValue = authHeader.Substring("Basic ".Length).Trim(); // 现在只是一个b64字符串
var decodedValue = Encoding.UTF8.GetString(Convert.FromBase64String(encodedValue));
var values = decodedValue.Split(":");
var username = values[0];
var password = values[1];
英文:
In the method, you can get the basic auth header sent by postman like this:
var header = Request.Headers["Authorization"].FirstOrDefault();
if(header == null) throw UnauthorizedException(); // Not sure this exception exists I just made it up
Then decode it, as it simply contains username:password encoded in base64 prefixed with "Basic ":
var encodedValue = authHeader.Substring("Basic ".Length).Trim(); // Now just a b64 string
var decodedValue = Encoding.UTF8.GetString(Convert.FromBase64String(encodedValue));
var values = decodedValue.Split(":");
var username = values[0];
var password = values[1];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论