Exemplo n.º 1
0
        public static async Task <AuthenticationResult> GetToken(OAuthContext oAuthContext)
        {
            // Get OAuth token using client credentials
            string tenantName = oAuthContext.tenantName;

            if (_authenticationContext == null)
            {
                _authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(oAuthContext.authUrl + "/" + tenantName, _tokenCache);
            }

            AuthenticationResult authenticationResult = null;

            if (oAuthContext.ObtainUserConsent)
            {
                // We need to get user consent

                FormGetUserPermission formGetPermission = new FormGetUserPermission(oAuthContext);
                if (formGetPermission.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string code = formGetPermission.Code;
                    // When we get our token, it will be cached in the TokenCache, so next time the silent calls will work
                    if (oAuthContext.cert == null)
                    {
                        ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCred);
                    }
                    else
                    {
                        ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCert);
                    }
                }
                return(authenticationResult);
            }

            if (oAuthContext.isNativeApplication)
            {
                if (oAuthContext.adminConsent)
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource,
                                                                                          oAuthContext.clientId,
                                                                                          new Uri(oAuthContext.redirectUrl),
                                                                                          new PlatformParameters(PromptBehavior.Always),
                                                                                          UserIdentifier.AnyUser,
                                                                                          "prompt=admin_consent");
                }
                else
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource, oAuthContext.clientId, new Uri(oAuthContext.redirectUrl), new PlatformParameters(PromptBehavior.Always));
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(oAuthContext.userId))
                {
                    // We have the UserId for the mailbox we want to access, so we'll try to get a token silently (we should have a cached token)
                    try
                    {
                        if (oAuthContext.cert == null)
                        {
                            ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCred, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        else
                        {
                            ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCert, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        return(authenticationResult);
                    }
                    catch (Exception ex)
                    {
                        _lastError = ex;
                    }
                }
            }
            return(authenticationResult);
        }
Exemplo n.º 2
0
        public async Task AcquireDelegateToken(string UserId = "")
        {
            string configError = String.Empty;

            if ((_authenticationUrl == String.Empty))
            {
                configError = "Authentication Url must be set.";
            }
            if ((_resourceUrl == String.Empty))
            {
                configError = "Resource Url must be set.";
            }
            if ((_tenantId == String.Empty))
            {
                configError = "Tenant Id must be set.";
            }
            if ((_applicationId == String.Empty))
            {
                configError = "ApplicationId must be set.";
            }
            if (_redirectUrl == String.Empty)
            {
                configError = "Redirect Url cannot be empty when acquiring a delegate token.";
            }
            if (!_isNativeApplication)
            {
                if ((_authCertificate == null) && String.IsNullOrEmpty(_clientSecret))
                {
                    configError = "Client (application) authentication must be specified.";
                }
            }
            if (!String.IsNullOrEmpty(configError))
            {
                _lastError = new Exception("Invalid configuration: " + configError);
                throw _lastError;
            }

            if (!String.IsNullOrEmpty(UserId))
            {
                if (_acquireTokenInProgress.Contains(UserId))
                {
                    // We're already requesting a token for this user
                    return;
                }
                _acquireTokenInProgress.Add(UserId);
            }

            OAuthContext oAuthContext = new OAuthContext();

            oAuthContext.adminConsent        = false;
            oAuthContext.authUrl             = _authenticationUrl;
            oAuthContext.clientId            = _applicationId;
            oAuthContext.resource            = _resourceUrl;
            oAuthContext.redirectUrl         = _redirectUrl;
            oAuthContext.tenantName          = _tenantId;
            oAuthContext.secretKey           = _clientSecret;
            oAuthContext.cert                = _authCertificate;
            oAuthContext.isV2Endpoint        = false;
            oAuthContext.isNativeApplication = _isNativeApplication;
            oAuthContext.ObtainUserConsent   = _obtainUserConsent;
            if (!String.IsNullOrEmpty(UserId))
            {
                oAuthContext.userId = UserId;
            }

            try
            {
                _authenticationResult = await GetToken(oAuthContext);
            }
            catch (Exception ex)
            {
                _lastError            = ex;
                _authenticationResult = null;
            }

            if (!String.IsNullOrEmpty(UserId))
            {
                _acquireTokenInProgress.Remove(UserId);
            }
        }