【发布时间】:2015-01-23 17:56:58
【问题描述】:
试图了解我计划使用 vb.net 为我的 ASP.net webapi 服务实现的自定义 OAuth2 授权服务器。我成功地使用 c# 创建了它,并且它没有任何错误,但是当我将代码转换为 vb 时,一切都开始崩溃。
当我使用我的 vb 代码运行时,我得到一个 NullReference 异常。
NullReferenceException: Object reference not set to an instance of an object.
Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3f.MoveNext()
下面是我自定义实现 OAuthAuthorizationServerProvider 的 c# 代码 -
public class CustomAuthorisationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string id, secret;
if (context.TryGetBasicCredentials(out id, out secret))
{
if (secret == "secret")
{
context.Validated();
}
}
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
if (context.UserName != context.Password)
{
context.Rejected();
return;
}
// create identity
var id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim("sub", context.UserName));
id.AddClaim(new Claim("role", "user"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "as:client_id", context.ClientId }
});
var ticket = new AuthenticationTicket(id, props);
context.Validated(ticket);
}
这是我的 Vb 转换代码 -
Public Class CustomAuthorisationServerProvider
Inherits OAuthAuthorizationServerProvider
Public Overrides Async Function ValidateClientAuthentication(context As OAuthValidateClientAuthenticationContext) As Task
Dim id As String, secret As String
If context.TryGetBasicCredentials(id, secret) Then
If secret = "secret" Then
context.Validated(id)
End If
End If
End Function
Public Overrides Function GrantResourceOwnerCredentials(context As OAuthGrantResourceOwnerCredentialsContext) As Task
If context.UserName <> context.Password Then
context.Rejected()
Return Nothing
End If
' create identity
Dim id = New ClaimsIdentity(context.Options.AuthenticationType)
id.AddClaim(New Claim("sub", context.UserName))
id.AddClaim(New Claim("role", "user"))
' create metadata to pass on to refresh token provider
Dim props = New AuthenticationProperties(New Dictionary(Of String, String)() From { _
{"as:client_id", context.ClientId} _
})
Dim ticket = New AuthenticationTicket(id, props)
context.Validated(ticket)
End Function
有人可以告诉我我哪里出错了吗?
【问题讨论】:
-
哪一行会导致 NRE?
-
当我调试时,ValidateClientAuthentication 方法被调用并且我没有收到任何错误,它甚至执行 context.Validate() 行也没有任何错误,但之后在客户端我得到错误。 GrantResourceOwnerCredentials 没有被调用。
-
调试的时候还发现,在ValidateClientAuthentication方法中,context.Parameters的值也是null。而在 c# 中,我得到了 grant_type、用户名和密码。不知道为什么参数在vb中为空
标签: vb.net oauth-2.0 asp.net-mvc-5 asp.net-web-api2