Search code examples
androidtokenexchangewebservices

Programmatically get EWS accesstoken


I have a working EWS connection, but at the moment I have to fill in my username and password everytime that I stop the app. Eventually alot of different users will use the application. Is there a way to programmatically get an accesstoken which I can store in the localstorrage? (I don't want to save the password)

    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

    ExchangeCredentials credentials = new WebCredentials(username, password);
    service.setCredentials(credentials);

    service.setUrl(new URI("https://domain/EWS/Exchange.asmx"));

Solution

  • It's called impersonation (the mail server admin must run a power shell command to assign superuser privileges to a designated mail account).

    Here is the link https://msdn.microsoft.com/en-us/library/office/dd633680(v=exchg.80).aspx

    Also here is a working example of how I use impersonation for hundreds of users. What you need is to store the usernames in a hashset or dictionary instead of an access token (there is no access token in EWS).

    Private _ExchangeServicesMainThread As New Dictionary(Of String, ExchangeService)
    Private _UserIdState As New Dictionary(Of String, Integer)
    Private _Connections As New Dictionary(Of String, StreamingSubscriptionConnection)
    Private _Subscriptions As New Dictionary(Of String, StreamingSubscription)
    
    Private Function InitializeService(pUsername As String) As ExchangeService
        Dim oExService As ExchangeService
        Dim strEmailAddress As String = pUsername & config.MailDomain
        Dim strAdminEmailAddress As String = config.ExchangeServerAdminUserName & config.MailDomain
    
            oExService = New ExchangeService(config.ExchangeVersion)
            oExService.UseDefaultCredentials = False
            oExService.Url = New Uri(config.SecureHTTP & config.EmailServer & config.ExchangeManagedAPIEndpoint)
            oExService.Credentials = New Net.NetworkCredential(config.ExchangeServerAdminUserName, config.ExchangeServerAdminPass, config.ActiveDirectoryDomain)
            oExService.ImpersonatedUserId = New ImpersonatedUserId(ConnectingIdType.SmtpAddress, strEmailAddress)
    
            Return oExService
    End Function
    

    Assuming you have an initialized dictionary of all the users then loop though your dictionary so that you assign an exchangeservice to each one of them and store this username/exchangeservice in a new dictionary

        For Each strUserName As String In _UserIdDictionary.Keys
            _ExchangeServicesMainThread.Add(strUserName, InitializeService(strUserName))
        Next