Android Question Logging in to MS 365

stu14t

Active Member
Licensed User
Longtime User
I've managed to work out the code to log into MS 365 and with the token that is sent back you should be able to perform various tasks. The only issue is, for some reason, with this code, you have to provide your password or 2FA twice before a token is passed back. Does anyone know why this may be?

Login to MS 365 and get Token:
Sub Process_Globals
    Private hc As OkHttpClient
    Private req As OkHttpRequest
    Private clientID As String = "baec15ce-80d1-4235-bde1-XXXXXXXXXXXX"
    Private redirectURI As String = "https://login.microsoftonline.com/common/oauth2/nativeclient"
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Dim WebView1 As WebView
    Dim prefs As SharedPreferences
    Dim wve As WebViewExtras

End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
End Sub

Sub Activity_Resume
    hc.Initialize("hc")
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Button1_Click
    Login
    End Sub
Sub Login
    
    Logout
    WebView1.Initialize("WebView1")
    
    wve.Initialize(WebView1)
    Dim settings As WebSettings = wve.GetSettings
    settings.SetCacheMode(settings.LOAD_NO_CACHE)
    wve.ClearFormData
    wve.ClearCache(True)
    Activity.AddView(WebView1, 0, 0, 100%x, 100%y)
    WebView1.LoadUrl("https://login.microsoftonline.com/common/oauth2/v2.0/logout") ' Log out from the Microsoft server
    
    Dim authUrl As String = $"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${clientID}&response_type=code&redirect_uri=${redirectURI}&response_mode=query&scope=https://graph.microsoft.com/.default&state=12345&prompt=login"$
    WebView1.LoadUrl(authUrl)
    
End Sub

Sub WebView1_OverrideUrl (Url As String) As Boolean
    If Url.StartsWith(redirectURI) Then
        Dim authCode As String = Url.SubString(Url.IndexOf("code=") + 5)
        authCode = authCode.SubString2(0, authCode.IndexOf("&"))
        GetToken(authCode)
        Return True
    End If
    Return False
End Sub

Sub GetToken(authCode As String)
    ' Start the resumable sub
    GetTokenImpl(authCode)
End Sub

Sub GetTokenImpl(authCode As String) As ResumableSub
    Dim params As Map
    params.Initialize
    params.Put("client_id", clientID)
    params.Put("code", authCode)
    params.Put("redirect_uri", redirectURI)
    params.Put("grant_type", "authorization_code")

    Dim sb As StringBuilder
    sb.Initialize
    For Each key As String In params.Keys
        sb.Append(key).Append("=").Append(params.Get(key)).Append("&")
    Next
    sb.Remove(sb.Length - 1, sb.Length) ' Remove the last "&"

    Dim req As OkHttpRequest
    req.InitializePost2("https://login.microsoftonline.com/common/oauth2/v2.0/token", sb.ToString.GetBytes("UTF8"))
    hc.Execute(req, 1)
    Wait For hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
    If TaskId = 1 Then
        Response.GetAsynchronously("response", File.OpenOutput(File.DirInternalCache, "response.txt", False), True, TaskId)
        Wait For response_StreamFinish (Success As Boolean, TaskId As Int)
        If Success Then
            Dim parser As JSONParser
            parser.Initialize(File.ReadString(File.DirInternalCache, "response.txt"))
            Dim root As Map = parser.NextObject
            Dim token As String = root.Get("access_token")
            ' Now you can use this token to make requests to the Graph API
            Log(token)
            SaveToken(token)
            ' Close the WebView
            WebView1.RemoveView
        Else
            Log("Error: " & LastException.Message)
        End If
        Return Null
    End If
    Return Null
End Sub

Sub Logout
    WebView1.LoadUrl("https://login.microsoftonline.com/common/oauth2/v2.0/logout") ' Log out from the Microsoft server
End Sub

Sub GetUserDetails(token As String)
    req.InitializeGet("https://graph.microsoft.com/v1.0/me")
    req.SetHeader("Authorization", "Bearer " & token)
    hc.Execute(req, 2)
End Sub

Sub SaveToken(token As String)
    prefs.Initialize("MyApp")
    prefs.SaveString("Token",token)
End Sub
 
Top