Login example in Visual Basic .NET

Sample VB code for generating the encrypted login parameter auth. Also shows how
to create a REST call.

The public key data for NEXTAPI is embedded in the code.


Imports System.Linq
Imports System.Text
Imports System.Security.Cryptography
Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Collections.Generic
Imports System.Web
Imports System.Net

Module nExtLogin

    Sub Main(ByVal args As String())
        Login(args(0), args(1), PUBLIC_KEY)
    End Sub

    Dim BASE_URL As String = "https://api.test.nordnet.se/next" 
    Dim VERSION As String = "2" 
    ' The public key for NEXTAPI from the XML file
    Dim PUBLIC_KEY As String = "<?xml version=""1.0""?>" + _
           "<RSAParameters xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema\"">" + _
           "<Exponent>AQAB</Exponent>" + _
           "<Modulus>5td/64fAicX2r8sN6RP3mfHf2bcwvTzmHrLcjJbU85gLROL+IXclrjWsluqyt5xtc/TCwM" + _
           "TfC/NcRVIAvfZdt+OPdDoO0rJYIY3hOGBwLQJeLRfruM8dhVD+/Kpu8yKzKOcRdne2hBb/mpkVtIl5av" + _
           "JPFZ6AQbICpOC8kEfI1DHrfgT18fBswt85deILBTxVUIXsXdG1ljFAQ/lJd/62J74vayQJq6l2DT663Q" + _
           "B8nLEILUKEt/hQAJGU3VT4APSfT+5bkClfRb9+kNT7RXT/pNCctbBTKujr3tmkrdUZiQiJZdl/O7LhI9" + _
           "9nCe6uyJ+la9jNPOuK5z6v72cXenmKZw==</Modulus>" + _
           "</RSAParameters>" 

    ' Login to nExt with username, password and the public key as XML.
    Sub Login(ByVal username As String, ByVal password As String, ByVal public_key As String)
        Dim RSA As RSACryptoServiceProvider = New System.Security.Cryptography.RSACryptoServiceProvider()

        ' Deserialize the public key
        Dim parameters As RSAParameters = Deserialize(Of RSAParameters)(public_key)

        ' Set the public key
        RSA.ImportParameters(parameters)

        ' Create timestamp (Unix timestamp in milliseconds)
        Dim timestamp As String = Math.Round((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds).ToString()

        ' Base64 encode each field and concatenate with ":" 
        Dim encoded As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username)) & ":" & Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(password)) & ":" & Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(timestamp))

        ' Encrypt
        Dim encrypted As Byte() = RSA.Encrypt(System.Text.Encoding.UTF8.GetBytes(encoded), False)

        ' Base 64 encode the blob.
        Dim blob As String = Convert.ToBase64String(encrypted)

        Dim restParameters As New Dictionary(Of String, String)()
        restParameters("service") = "NEXTAPI" 
        restParameters("auth") = blob

        ' Send request and write response
        System.Console.WriteLine(SendRequest("POST", "login", restParameters))
    End Sub

    ' Do a HTTP request with parameters
    Function SendRequest(ByVal method As String, ByVal requestPath As String, ByVal parameters As Dictionary(Of String, String)) As String
        Dim retVal As String = "" 
        Try
            ' Create the URL
            Dim address As New Uri(BASE_URL & "/" & VERSION & "/" & requestPath)

            ' Create request
            Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)

            request.Method = "POST" 
            request.Accept = "application/json" 
            request.ContentType = "application/x-www-form-urlencoded" 

            If parameters IsNot Nothing AndAlso (method = "POST" OrElse method = "PUT" OrElse method = "DELETE") Then
                request.ContentType = "application/x-www-form-urlencoded" 

                Dim byteData As Byte() = UTF8Encoding.UTF8.GetBytes(CreateParameterList(parameters))

                request.ContentLength = byteData.Length

                ' Write data  
                Using postStream As Stream = request.GetRequestStream()
                    postStream.Write(byteData, 0, byteData.Length)
                End Using
            End If
            ' Get response  
            Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
                ' Get the response stream  
                Dim reader As New StreamReader(response.GetResponseStream())

                ' Console application output  
                retVal += reader.ReadToEnd()
            End Using
        Catch e As System.Net.WebException
            System.Console.WriteLine("REST call failed. Message: " & e.Message)
        End Try
        Return retVal
    End Function

    ' Create a list of parameters
    Function CreateParameterList(ByVal parameters As Dictionary(Of String, String)) As String
        ' Create parameter list
        Dim data As New StringBuilder()
        If parameters IsNot Nothing Then
            For Each parameter As KeyValuePair(Of String, String) In parameters
                data.Append(If(data.Length = 0, "", "&"))
                data.Append(parameter.Key & "=" & HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(parameter.Value)))
            Next
        End If
        Return data.ToString()

    End Function

    ' Deserialize an object of type T from XML.
    Function Deserialize(Of T)(ByVal xml As String) As T
        Dim ms As New MemoryStream(Encoding.Unicode.GetBytes(xml))

        Dim reply As T = Activator.CreateInstance(Of T)()

        Dim serializer As New XmlSerializer(reply.[GetType]())

        reply = DirectCast(serializer.Deserialize(ms), T)

        ms.Close()
        Return reply
    End Function

End Module