.net web 可执行文件到 .net web api 使用 BASIC 身份验证时出现 401 错误
.net web executable to .net web api 401 error using BASIC authentication
上班不让装fiddler,有点瞎了。
我是 运行 网络 api 和本地主机上的网络可执行文件,通过 visual studio
的两个独立实例
我相当确定我的 Web API 工作正常 我在网络浏览器中手动输入 URL 它要求我输入用户 ID 和密码然后 returns 我的 JSON。
调用 web api 的 web 可执行文件也工作正常,直到我尝试将 BASIC 身份验证添加到控制器方法,现在我收到 401 错误。
这是我的可执行代码。
Public Function get_vsmric_webApi(ByRef sErrorDescription As String) As Boolean
Try
Using proxy As New WebClient()
Dim myurl As String = ConfigurationManager.AppSettings("WEBAPI_URL") & "vsmric"
Dim userName As String = "QBERT"
Dim passWord As String = "Qb3RT!"
Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord))
proxy.Headers(HttpRequestHeader.Authorization) = "BASIC" + credentials
Dim json As String = proxy.DownloadString(myurl)
Dim rics As List(Of DB2VSMRIC) = JsonConvert.DeserializeObject(Of List(Of DB2VSMRIC))(json)
Dim list As List(Of DB2VSMRIC) = rics.Where(Function(p) HasData(p.Cage)).ToList
If list.Count < 1 Then
sErrorDescription = "No VSMRIC w/Cage records found."
Else
dictShipFrom = New Dictionary(Of String, String)
dictShipFrom = list.ToDictionary(Function(p) p.Ric, Function(p) p.Dodaac)
dictCage = New Dictionary(Of String, String)
dictCage = list.ToDictionary(Function(p) p.Ric, Function(p) p.Cage)
End If
End Using
Catch ex As Exception
sErrorDescription = "Exception in get_vsmric_webApi(), " & ex.Message
Return False
Finally
End Try
Return True
End Function
这里是网上的控制器方法api
[CustomAuthentication]
[CustomAuthorization("qbert")]
public class VSMRICController : ApiController
{
/// <summary>
/// Returns all records in the DB2 VSM RIC table
/// </summary>
/// <param name="id">The ID of the data.</param>
public IEnumerable<DB2VSMRIC> Get()
{
return DB2VSMRICRepository.getAll();
}
这是过滤器(用于身份验证)
public class CustomAuthenticationAttribute : Attribute, IAuthenticationFilter
{
// the job of the AuthenticateAsync method is to examine the request to see whether it contains
// the information that is required to identify a user. Information about the request is provided
// through an instance of the HttpAuthenticationContext class.
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
context.Principal = null;
AuthenticationHeaderValue authentication = context.Request.Headers.Authorization;
if (authentication != null && authentication.Scheme == "Basic")
{
string[] authData = Encoding.ASCII.GetString(Convert.FromBase64String(
authentication.Parameter)).Split(':');
context.Principal
= ApiManager.AuthenticateUser(authData[0], authData[1]);
}
if (context.Principal == null)
{
context.ErrorResult
= new UnauthorizedResult(new AuthenticationHeaderValue[]{
new AuthenticationHeaderValue("Basic")}, context.Request);
}
return Task.FromResult<object>(null);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.FromResult<object>(null);
}
public bool AllowMultiple
{
get { return false; }
}
}
我再次确信 Web API 工作正常,因为我可以通过直接导航到 url 并在任何 Web 浏览器中提供凭据来访问 JSON。我在想我在可执行文件中设置 header 时做错了什么。有什么想法吗? (我通过 visual studio 的 2 个实例在本地 运行 一切)
问题出在您设置基本身份验证的那一行。应该是
... = "Basic " + 凭据
而不是
... = "BASIC" + 凭据
区分大小写和space。
编码愉快。
上班不让装fiddler,有点瞎了。
我是 运行 网络 api 和本地主机上的网络可执行文件,通过 visual studio
的两个独立实例我相当确定我的 Web API 工作正常 我在网络浏览器中手动输入 URL 它要求我输入用户 ID 和密码然后 returns 我的 JSON。
调用 web api 的 web 可执行文件也工作正常,直到我尝试将 BASIC 身份验证添加到控制器方法,现在我收到 401 错误。
这是我的可执行代码。
Public Function get_vsmric_webApi(ByRef sErrorDescription As String) As Boolean
Try
Using proxy As New WebClient()
Dim myurl As String = ConfigurationManager.AppSettings("WEBAPI_URL") & "vsmric"
Dim userName As String = "QBERT"
Dim passWord As String = "Qb3RT!"
Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord))
proxy.Headers(HttpRequestHeader.Authorization) = "BASIC" + credentials
Dim json As String = proxy.DownloadString(myurl)
Dim rics As List(Of DB2VSMRIC) = JsonConvert.DeserializeObject(Of List(Of DB2VSMRIC))(json)
Dim list As List(Of DB2VSMRIC) = rics.Where(Function(p) HasData(p.Cage)).ToList
If list.Count < 1 Then
sErrorDescription = "No VSMRIC w/Cage records found."
Else
dictShipFrom = New Dictionary(Of String, String)
dictShipFrom = list.ToDictionary(Function(p) p.Ric, Function(p) p.Dodaac)
dictCage = New Dictionary(Of String, String)
dictCage = list.ToDictionary(Function(p) p.Ric, Function(p) p.Cage)
End If
End Using
Catch ex As Exception
sErrorDescription = "Exception in get_vsmric_webApi(), " & ex.Message
Return False
Finally
End Try
Return True
End Function
这里是网上的控制器方法api
[CustomAuthentication]
[CustomAuthorization("qbert")]
public class VSMRICController : ApiController
{
/// <summary>
/// Returns all records in the DB2 VSM RIC table
/// </summary>
/// <param name="id">The ID of the data.</param>
public IEnumerable<DB2VSMRIC> Get()
{
return DB2VSMRICRepository.getAll();
}
这是过滤器(用于身份验证)
public class CustomAuthenticationAttribute : Attribute, IAuthenticationFilter
{
// the job of the AuthenticateAsync method is to examine the request to see whether it contains
// the information that is required to identify a user. Information about the request is provided
// through an instance of the HttpAuthenticationContext class.
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
context.Principal = null;
AuthenticationHeaderValue authentication = context.Request.Headers.Authorization;
if (authentication != null && authentication.Scheme == "Basic")
{
string[] authData = Encoding.ASCII.GetString(Convert.FromBase64String(
authentication.Parameter)).Split(':');
context.Principal
= ApiManager.AuthenticateUser(authData[0], authData[1]);
}
if (context.Principal == null)
{
context.ErrorResult
= new UnauthorizedResult(new AuthenticationHeaderValue[]{
new AuthenticationHeaderValue("Basic")}, context.Request);
}
return Task.FromResult<object>(null);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.FromResult<object>(null);
}
public bool AllowMultiple
{
get { return false; }
}
}
我再次确信 Web API 工作正常,因为我可以通过直接导航到 url 并在任何 Web 浏览器中提供凭据来访问 JSON。我在想我在可执行文件中设置 header 时做错了什么。有什么想法吗? (我通过 visual studio 的 2 个实例在本地 运行 一切)
问题出在您设置基本身份验证的那一行。应该是
... = "Basic " + 凭据
而不是
... = "BASIC" + 凭据
区分大小写和space。
编码愉快。