我的 Web API 的自定义 OAuth 授权服务器



试图绕过自定义 OAuth2 授权服务器,该服务器计划使用 vb.net 为我的 ASP.net webapi 服务实现。我能够使用 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

有人可以告诉我我出了什么问题吗?

我处于同样的情况,几乎在阅读您的帖子时找到了解决方案。

您所要做的就是返回 Task.FromResult(0)

Return Task.FromResult(0)

最新更新