1

webservicehost クラスでの認証が認証標準に完全に準拠していないことは承知しています (ユーザーが間違った資格情報を入力したときに、別の資格情報のセットを要求するのではなく、403 禁止を返します)。

この基本認証 (セッション開始時のユーザー名とパスワード、HTTPS は不要 - 下の図を参照) は小規模なホーム プロジェクトのニーズに合っているため、引き続き実装したいと考えています。

必要な認証の種類

myService のコードは次のとおりです。

Imports System.IO
Imports System.Text
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.ServiceModel.Channels

<ServiceContract()>
Public Class myService
    <OperationContract(), WebGet(UriTemplate:="/xml/{argument1}/{argument2}")>
    Public Function XML(argument1 As String, argument2 As String) As Stream
        requestCounter += 1
        Console.WriteLine("xml data request at " & DateTime.Now.ToString() & ", request count= " & requestCounter)
        Console.WriteLine(WebOperationContext.Current.IncomingRequest.UserAgent.ToString())
        Return _ReturnXML("<xmlresponse><data><argument1>" & argument1 & "</argument1><argument2>" & argument2 & "</argument2></data><server><serverlivesince>" & serverStart.ToString() & "</serverlivesince><pageservetime>" & DateTime.Now.ToString() & "</pageservetime><requestcount>" & requestCounter & "</requestcount></server></xmlresponse>")
        'returns the first two parameters, and the time and date
    End Function

    Private Shared Function _ReturnXML(_result As String) As Stream
        Dim data = Encoding.UTF8.GetBytes(_result)

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml; charset=utf-8"
        WebOperationContext.Current.OutgoingResponse.ContentLength = data.Length

        Return New MemoryStream(data)
    End Function
End Class

次に、HTML を返すだけでなく、他のパラメーターの組み合わせを受け入れる同様のコードがあります。

私の Main クラスでは、このサービスを次のようにインスタンス化して開きました。

Dim varWebService = New WebServiceHost(GetType(MyWebService), New Uri("http://0.0.0.0/"))
varWebService.Open()

この単純な認証を実装するためのコードを誰かに提供してもらえますか? または、完全なチュートリアルを教えてください。助けてくれてありがとう

4

3 に答える 3

0

Shaydo、あなたは最高です !ありがとうございました!それが私が何週間も探したものです!https: VB.NET: で使用するために vb コードを拡張しました。

Public Class AuthenticatedWebServiceHost
   Inherits WebServiceHost
    Public Sub New(ByVal type As Type, ByVal url As Uri, MyThumbprint As String)
        Dim desc As IDictionary(Of String, ContractDescription) = Nothing
        MyBase.InitializeDescription(type, New UriSchemeKeyedCollection())
        MyBase.CreateDescription(desc)
        Dim val = desc.Values.First()
        Dim binding As WebHttpBinding = New WebHttpBinding()
        'binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly
        binding.Security.Mode = BasicHttpsSecurityMode.TransportWithMessageCredential
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic
        MyBase.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom
        MyBase.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = New CustomUserNamePasswordValidator()
        MyBase.Credentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, MyThumbprint)
        MyBase.AddServiceEndpoint(val.ContractType, binding, url)
    End Sub

    Public Shared ReadOnly Property UserName As String
        Get
            If OperationContext.Current Is Nothing Then Return Nothing
            If OperationContext.Current.ServiceSecurityContext Is Nothing Then Return Nothing
            If OperationContext.Current.ServiceSecurityContext.PrimaryIdentity Is Nothing Then Return Nothing
            Return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
        End Get
    End Property

    Public Class CustomUserNamePasswordValidator
        Inherits UserNamePasswordValidator
        Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
            If userName <> password Then
                Console.WriteLine("Error: Access denied")
                Throw New SecurityAccessDeniedException()
            End If
        End Sub
    End Class
End Class
于 2020-06-11T22:57:11.820 に答える