【问题标题】:Token authentication with aspnet web api 2.0使用 aspnet web api 2.0 进行令牌认证
【发布时间】:2015-08-19 21:19:05
【问题描述】:

我是 web api 的新手,我注意到那里不支持会话。我发现令牌是进行身份验证的最佳方式,但我不知道如何在我的应用程序中实现它。我发现的一切对我来说都没有帮助而且太复杂了。

难道没有这么简单的东西吗?

Public Sub Login(<FromBody()> ByVal Email As String, <FromBody()> ByVal Password As String)
    cmd.CommandText = "[dbo].[Login]"
    cmd.CommandType = Data.CommandType.StoredProcedure
    cmd.Parameters.Add("@Email", Data.SqlDbType.NVarChar).Value = Email
    cmd.Parameters.Add("@Password", Data.SqlDbType.NVarChar).Value = Password
    cmd.Connection.Open()
    Dim rd As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader()
    If rd.HasRows Then
        While rd.Read()
            **GENERATE A TOKEN AND LINK TO rd.Item("IdUser")**
            **Return TOKEN**
            (previously I would use Session("id") = rd.Item("IdUser"))
        End While
        Return "Ok"
    Else
        ...
    End If
    cmd.Connection.Close()
    Return True
End Sub

【问题讨论】:

  • 好吧,我开始明白了,在你的链接中我找到了这个asp.net/web-api/overview/security/basic-authentication如果我明白的话告诉我..每个http请求都会调用这个类,它从身份验证标头中获取用户名和密码,所以我应该发送用户名和密码,而不是令牌,对吗?所以现在我只需要找到一种方法来生成令牌,发送到客户端并保存到数据库吗?
  • 我了解身份验证和令牌的工作原理,但我仍然不了解如何实现它我发现的所有资源都过于复杂且不适合我的解决方案。我只需要如何在我的登录 api 中生成一个令牌,以及如何在 VB 中的每个受保护的 api 之前检查它
  • 您可以使用凭据生成 base64 编码字符串,并要求用户在每次调用时传递它。

标签: asp.net vb.net token asp.net-web-api2


【解决方案1】:

好的,我只是做了一些工作(感谢 Amit Kumar Ghosh),希望对某人有用

这在 App_start 中

Imports System.Net
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Security.Principal
Imports System.Web.Security

Namespace Glossario.MessageHandler
    Public Class BasicAuthenticationMessageHandler
        Inherits DelegatingHandler
        Protected Overrides Function SendAsync(request As HttpRequestMessage, cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
            Dim myCredentials As Credentials = Nothing
            Dim identity As GenericIdentity = Nothing

            If (request.Headers.Authorization IsNot Nothing) Then
                myCredentials = ExtractCredentials(request.Headers.Authorization)
                If IsValidUser(myCredentials) Then
                    identity = New GenericIdentity(myCredentials.UserName, "Basic")
                    request.GetRequestContext().Principal = New GenericPrincipal(identity, New String(-1) {})
                End If
            End If
            Return MyBase.SendAsync(request, cancellationToken)
        End Function

        Private Function ExtractCredentials(authHeader As AuthenticationHeaderValue) As Credentials
            Dim myCredentials As Credentials = Nothing
            Try
                If authHeader.Scheme = "Basic" Then
                    Dim encodedUserPass = authHeader.Parameter.Trim()
                    Dim encoding = System.Text.Encoding.GetEncoding("iso-8859-1")
                    Dim userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass))
                    Dim parts = userPass.Split(":".ToCharArray())

                    myCredentials = New Credentials()
                    myCredentials.UserName = parts(0)
                    myCredentials.Password = parts(1)
                End If
            Catch ex As Exception
                myCredentials = Nothing
            End Try
            Return myCredentials
        End Function

        Private Function IsValidUser(myCredentials As Credentials) As Boolean
            Dim result As Boolean = False

            If (myCredentials IsNot Nothing) Then
                    cmd.CommandText = "[dbo].[Login]" 'CHANGE WITH YOUR OWN CODE
                    cmd.CommandType = Data.CommandType.StoredProcedure
                    cmd.Parameters.Add("@Email", Data.SqlDbType.NVarChar).Value = MyCredentials.UserName
                    cmd.Parameters.Add("@Password", Data.SqlDbType.NVarChar).Value = MyCredentials.Password
                    cmd.Connection.Open()
                    Dim rd As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader()
                    If rd.HasRows Then
                        While rd.Read()
                            Result = True
                        End While
                    End If
                    cmd.Connection.Close()
            End If
            Return result
        End Function

        Private Class Credentials
            Public Property UserName() As String
            Public Property Password() As String
        End Class
    End Class
End Namespace

在 global.asax Protected Sub Application_Start()中

    GlobalConfiguration.Configuration.MessageHandlers.Add(New Glossario.MessageHandler.BasicAuthenticationMessageHandler())

【讨论】:

  • 在 HTTP 401 的情况下,服务器有责任返回挑战令牌作为响应,客户端必须在后续请求中发送该令牌。
猜你喜欢
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 2011-12-12
相关资源
最近更新 更多