public static bool MakeMeAvailable(HttpClient httpClient, AuthenticationResult ucwaAuthenticationResult, String ucwaMakeMeAvailableRootUri,
            UcwaMakeMeAvailableObject ucwaMyPresenceObject)
        {
            string makeMeAvailableResults = string.Empty;
            Console.WriteLine("URI is " + ucwaMakeMeAvailableRootUri);

            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ucwaAuthenticationResult.AccessToken);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var makeMeAvailablePostData = JsonConvert.SerializeObject(ucwaMyPresenceObject);
            Console.WriteLine("MakeMeAvailable POST data is " + makeMeAvailablePostData);
            var httpResponseMessage =
                httpClient.PostAsync(ucwaMakeMeAvailableRootUri, new StringContent(makeMeAvailablePostData, Encoding.UTF8,
                "application/json")).Result;
            Console.WriteLine("MakeMeAvailable response is " + httpResponseMessage.Content.ReadAsStringAsync().Result);
            Console.WriteLine("MakeMeAvailable response should be empty");

            if (httpResponseMessage.Content.ReadAsStringAsync().Result == String.Empty)
            {
                Console.WriteLine("MakeMeAvailable call succeeded");
                return true;
            }

            Console.WriteLine("MakeMeAvailable call failed");
            return false;
        }
Esempio n. 2
0
      public static async Task<string> GetDrivesApiCallForSelectedFile( this SharePointOnlineUri fileHandlerFileGetOrPutUri, Guid FileHandlerFileId, AuthenticationResult SharepointAdalAuthResult )
      {
         using ( var context = new ClientContext( fileHandlerFileGetOrPutUri.GetSharePointWebUrlFromFileHandlerGetPutUri() ) )
         {
            context.ExecutingWebRequest += ( sender, e ) =>
                                       {
                                          e.WebRequestExecutor.RequestHeaders.Add( "Authorization", SharepointAdalAuthResult.CreateAuthorizationHeader() );
                                       };

            var webRequestUrl = await Task.Run( () =>
                                       {
                                          return GetSharePointMetaData( context, FileHandlerFileId );
                                       } );

            JObject oneDriveResult = await Task.Run( async () =>  
                                       {
                                          string result = string.Empty;
                                          using ( var request = new WebClient() )
                                          {
                                             request.Headers.Add( "Authorization", SharepointAdalAuthResult.CreateAuthorizationHeader() );
                                             result = await request.DownloadStringTaskAsync( webRequestUrl );
                                          }
                                          return JObject.Parse( result );
                                       } );

            var driveId = oneDriveResult["parentReference"]["driveId"].ToString();
            var itemId = oneDriveResult["id"].ToString();

            return $"drives/{driveId}/items/{itemId}";

         }
      }
Esempio n. 3
0
 public TokenCacheInfo(string tenantId, string appId, string appKey, string resource, AuthenticationResult result)
     : this(resource, result)
 {
     AppId = appId;
     AppKey = appKey;
     TenantId = tenantId;
 }
        public async void Authenticate()
        {
            BuildAuthority();
            if(WeHaveEnoughInfo())
            {
                Context     = new AuthenticationContext(Authority);

                if (Context.TokenCache.ReadItems().Count() > 0)
                    Context = new AuthenticationContext(Context.TokenCache.ReadItems().First().Authority);
                try
                {

                    Result = await Context.AcquireTokenAsync(GraphResourceUri, ClientId, ReturnUri);

                    Log.WritetoLog("Authentication successful");
                    Log.WritetoLog("Signed in as: " + Result.UserInfo.GivenName + " " + Result.UserInfo.FamilyName);
                    Log.WritetoLog("Token type: " + Result.AccessTokenType);
                    Log.WritetoLog("Identity provider: " + Result.UserInfo.IdentityProvider);
                }
                catch (Exception ex)
                {
                    SetErrorMessage(ex.Message);
                    ShowError();
                }
            }
            else
            {
                SetErrorMessage("Looks like we're missing some info from you."                                                      );
                ShowError();
            }
        }
 public ServicePrincipalAccessToken(AdalConfiguration configuration, AuthenticationResult authResult, ServicePrincipalTokenProvider tokenProvider, string appId)
 {
     Configuration = configuration;
     AuthResult = authResult;
     this.tokenProvider = tokenProvider;
     this.appId = appId;
 }
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var userCredential        = new ActiveDirectory.UserCredential();

                ActiveDirectory.AuthenticationResult result = await AdalExtentions.AcquireTokenAsync(authenticationContext,
                                                                                                     resource,
                                                                                                     clientId,
                                                                                                     userCredential);

                return(new Result(result));
            }
            catch (ActiveDirectory.AdalException exception)
            {
                throw new AuthenticationException(exception);
            }
        }
        public async Task<bool> AuthenticateAsync()
        {
            await GetConfigAsync();

            // prompts the user for authentication
            _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri);

            var accessToken = await GetTokenAsync();

            // instantiate an ActiveDirectoryClient to query the Graph API
            var activeDirectoryGraphApiClient = new ActiveDirectoryClient(
                new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId),
                () => Task.FromResult<string>(accessToken)
            );

            // query the Azure Graph API for some detailed user information about the logged in user
            var userFetcher = activeDirectoryGraphApiClient.Me.ToUser();
            var user = await userFetcher.ExecuteAsync();

            // record some info about the logged in user with Xamarin Insights
            Insights.Identify(
                _AuthenticationResult.UserInfo.UniqueId, 
                new Dictionary<string, string> 
                {
                    { Insights.Traits.Email, user.UserPrincipalName },
                    { Insights.Traits.FirstName, user.GivenName },
                    { Insights.Traits.LastName, user.Surname },
                    { "Preferred Language", user.PreferredLanguage }
                }
            );

            return true;
        }
Esempio n. 8
0
      internal static JObject JSONResponse( string url, HttpMethod method, AuthenticationResult authResult, string apiPayload = "" )
      {
         HttpWebRequest webClientRequest;
         webClientRequest = WebRequest.CreateHttp( new Uri( url ) );
         webClientRequest.Method = method.ToString();
         webClientRequest.Headers.Add( "Authorization", authResult.CreateAuthorizationHeader() );
         if ( method != HttpMethod.Get )
         {
            using ( var writer = new StreamWriter( webClientRequest.GetRequestStream() ) )
            {
               writer.Write( apiPayload );

            }
         }
         WebResponse response;
         JObject jsonResponse = null;
         try
         {
            response = webClientRequest.GetResponse();
         }
         catch ( WebException webEx )
         {
            response = webEx.Response;
         }
         using ( var reader = new StreamReader( response.GetResponseStream() ) )
         {
            jsonResponse = JObject.Parse( reader.ReadToEnd() );
         }
         return jsonResponse;
      }
        private static async Task SaveAuthToken(AuthState authState, AuthenticationResult authResult)
        {
            var idToken = SessionToken.ParseJwtToken(authResult.IdToken);
            string username = null;
            var userNameClaim = idToken.Claims.FirstOrDefault(x => x.Type == "upn");
            if (userNameClaim != null)
                username = userNameClaim.Value;

            using (var db = new AddInContext())
            {
                var existingToken =
                                await
                                    db.SessionTokens.FirstOrDefaultAsync(
                                        t => t.Provider == Settings.AzureADAuthority && t.Id == authState.stateKey);
                if (existingToken != null)
                {
                    db.SessionTokens.Remove(existingToken);
                }
                var token = new SessionToken()
                {
                    Id = authState.stateKey,
                    CreatedOn = DateTime.Now,
                    AccessToken = authResult.AccessToken,
                    Provider = Settings.AzureADAuthority,
                    Username = username
                };
                db.SessionTokens.Add(token);
                await db.SaveChangesAsync();
            }
        }
Esempio n. 10
0
        private async Task <string> AuthorizationHeaderADAL()
        {
            if (!string.IsNullOrEmpty(_authorizationHeader) &&
                (DateTime.UtcNow.AddSeconds(60) < AuthenticationResultADAL.ExpiresOn))
            {
                return(_authorizationHeader);
            }

            var uri = new UriBuilder(_settings.AzureAuthEndpoint)
            {
                Path = _settings.AadTenant
            };

            var    aosUriAuthUri = new Uri(_settings.AosUri);
            string aosUriAuth    = aosUriAuthUri.GetLeftPart(UriPartial.Authority);

            var authenticationContext = new AuthenticationContext(uri.ToString(), validateAuthority: false);

            if (_settings.UseServiceAuthentication)
            {
                var credentials = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_settings.AadClientId.ToString(), _settings.AadClientSecret);

                AuthenticationResultADAL = await authenticationContext.AcquireTokenAsync(aosUriAuth, credentials);
            }
            else
            {
                var credentials = new UserPasswordCredential(_settings.UserName, _settings.UserPassword);

                AuthenticationResultADAL = await authenticationContext.AcquireTokenAsync(aosUriAuth, _settings.AadClientId.ToString(), credentials);
            }

            return(_authorizationHeader = AuthenticationResultADAL.CreateAuthorizationHeader());
        }
Esempio n. 11
0
        public async Task <string> AuthenticatePowerBIUser(LoginModel loginModel)
        {
            try
            {
                //The client id that Azure AD created when you registered your client app.
                string clientID = System.Configuration.ConfigurationManager.AppSettings["powerBIClientId"];

                //RedirectUri you used when you register your app.
                //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
                // You can use this redirect uri for your client app
                //string redirectUri = "urn:ietf:wg:oauth:2.0:oob";

                //Resource Uri for Power BI API
                string resourceUri = System.Configuration.ConfigurationManager.AppSettings["powerBIresourceUri"];

                //OAuth2 authority Uri
                string authorityUri = System.Configuration.ConfigurationManager.AppSettings["powerBIauthorityUri"];

                string username = loginModel.UserName;
                string password = loginModel.Password;
                //Get access token:
                // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
                // AcquireToken will acquire an Azure access token
                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                AuthenticationContext authContext = new AuthenticationContext(authorityUri);
                var credential = new UserPasswordCredential(username, password);
                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult res = authContext.AcquireTokenAsync(resourceUri, clientID, credential).Result;

                return(res.AccessToken);
            }
            catch (Exception ex)
            {
                return("PowerBI Authentication failed");
            }
        }
Esempio n. 12
0
        public async Task<bool> AuthenticateAsync()
        {
            await GetConfigAsync();

            // prompts the user for authentication
            _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri);

            var accessToken = await GetTokenAsync();

            // instantiate an ActiveDirectoryClient to query the Graph API
            var activeDirectoryGraphApiClient = new ActiveDirectoryClient(
                new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId),
                () => Task.FromResult<string>(accessToken)
            );

            // query the Azure Graph API for some detailed user information about the logged in user
            //This is done differently based on platform because if this is not awaited in iOS, it crashes
            //the app. Android is done this way to correct login issues that were previously occurring.
            if (Xamarin.Forms.Device.OS == TargetPlatform.Android)
            {
                Task.Run(() =>
                    {
                        LogUserInfo(activeDirectoryGraphApiClient);
                    });
            }
            else
            {
                await Task.Run(async () =>
                    {
                        LogUserInfo(activeDirectoryGraphApiClient);
                    });
            }

            return true;
        }
Esempio n. 13
0
        public static async Task <HttpResponseMessage> CrmWebApiRequest(string apiRequest, HttpContent requestContent, string requestType, IConfiguration ConfigurationManager)
        {
            AuthenticationContext authContext = new AuthenticationContext(ConfigurationManager["AdOath2AuthEndpoint"], false);
            UserCredential        credentials = new UserCredential(ConfigurationManager["CrmUsername"]);

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult tokenResult = await authContext.AcquireTokenAsync(ConfigurationManager["CrmServerUrl"],
                                                                                                                                   ConfigurationManager["AdClientId"], credentials);

            HttpResponseMessage apiResponse;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(ConfigurationManager["CrmServerUrl"]);
                httpClient.Timeout     = new TimeSpan(0, 2, 0);
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.AccessToken);

                if (requestType == "retrieve")
                {
                    apiResponse = await httpClient.GetAsync(apiRequest);
                }
                else if (requestType == "create")
                {
                    apiResponse = await httpClient.PostAsync(apiRequest, requestContent);
                }
                else
                {
                    apiResponse = null;
                }
            }
            return(apiResponse);
        }
        //Get access token:
        // To call a Data Catalog REST operation, create an instance of AuthenticationContext and call AcquireToken
        // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
        // To install the Active Directory Authentication Library NuGet package in Visual Studio,
        //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the NuGet Package Manager Console.
        static AuthenticationResult AccessToken()
        {
            if (authResult == null)
            {
                //Resource Uri for Data Catalog API
                string resourceUri = "https://datacatalog.azure.com";

                //To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
                string clientId = clientIDFromAzureAppRegistration;

                //A redirect uri gives AAD more details about the specific application that it will authenticate.
                //Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app.
                string redirectUri = "https://login.live.com/oauth20_desktop.srf";

                // Create an instance of AuthenticationContext to acquire an Azure access token
                // OAuth2 authority Uri
                string authorityUri = "https://login.windows.net/common/oauth2/authorize";
                AuthenticationContext authContext = new AuthenticationContext(authorityUri);

                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                //  AcquireToken takes a Client Id that Azure AD creates when you register your client app.
                authResult = authContext.AcquireToken(resourceUri, clientId, new Uri(redirectUri), PromptBehavior.RefreshSession);
            }

            return authResult;
        }
        internal static AuthenticationResult From(OriginalAuthenticationResult originalAuthResult)
        {
            var result = new AuthenticationResult();

            result.Initialize(originalAuthResult);
            return(result);
        }
Esempio n. 16
0
        public static async Task <GraphServiceClient> GetGraphServiceClient2()
        {
            var authentication = new
            {
                Authority             = "https://graph.microsoft.com/",
                Directory             = WebConfigurationManager.AppSettings["ida:TenantId"],
                Application           = WebConfigurationManager.AppSettings["ida:ClientId"],
                ClientSecret          = WebConfigurationManager.AppSettings["ida:ClientSecret"],
                GraphResourceEndPoint = "v1.0",
                Instance = WebConfigurationManager.AppSettings["ida:AADInstance"],
                Domain   = WebConfigurationManager.AppSettings["ida:Domain"]
            };
            var graphAPIEndpoint = $"{authentication.Authority}{authentication.GraphResourceEndPoint}";
            var newAuth          = $"{authentication.Instance}{authentication.Directory}";
            //var newAuth2 = $"{authentication.Instance}{authentication.Domain}";

            AuthenticationContext authenticationContext = new AuthenticationContext(newAuth);

            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred
                = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(authentication.Application, authentication.ClientSecret);
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult
                = await authenticationContext.AcquireTokenAsync(authentication.Authority, clientCred);

            var token = authenticationResult.AccessToken;
            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) => {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
                return(Task.FromResult(0));
            });

            var graphClient = new GraphServiceClient(graphAPIEndpoint, delegateAuthProvider);

            return(graphClient);
        }
 public AzureADAuthentication()
 {
     Log.WritetoLog("Authentication object initialized");
     Tenant =        string.Empty;
     ClientId =      string.Empty;
     ErrorMessage =  string.Empty;
     Context =       null;
     Result =        null;
 }
Esempio n. 18
0
 public TokenCacheInfo(string resource, AuthenticationResult result)
 {
     AccessToken = result.AccessToken;
     DisplayableId = result.UserInfo == null ? null : result.UserInfo.DisplayableId;
     ExpiresOn = result.ExpiresOn;
     RefreshToken = result.RefreshToken;
     Resource = resource;
     TenantId = result.TenantId;
 }
        /// <summary>
        /// Create an application token provider that can retrieve tokens for the given application from the given context, using the given audience 
        /// and credential store.
         /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
        /// for detailed instructions on creating an Azure Active Directory application.
       /// </summary>
        /// <param name="context">The authentication context to use when retrieving tokens.</param>
        /// <param name="tokenAudience">The token audience to use when retrieving tokens</param>
        /// <param name="clientId">The client Id for this active directory application</param>
        /// <param name="credentialStore">The source of authentication information for this application.</param>
        /// <param name="authenticationResult">The authenticationResult of initial authentication with the application credentials.</param>
        public ApplicationTokenProvider(AuthenticationContext context, string tokenAudience, string clientId,
             IApplicationCredentialProvider credentialStore, AuthenticationResult authenticationResult)
        {
            if (authenticationResult == null)
            {
                throw new ArgumentNullException("authenticationResult");
            }

            Initialize(context, tokenAudience, clientId, credentialStore, authenticationResult, authenticationResult.ExpiresOn);
        }
Esempio n. 20
0
        private void getAccessToken()
        {
            string resourceUri = "https://analysis.windows.net/powerbi/api";
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            _token = authContext.AcquireToken(resourceUri, this._clientId,
                new Uri(redirectUri), PromptBehavior.Always);
        }
 private void DisplayToken(AuthenticationResult result)
 {
     if (!string.IsNullOrEmpty(result.AccessToken))
     {
         this.AccessToken.Text = result.AccessToken;
     }
     else
     {
         this.AccessToken.Text = result.ErrorDescription;
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SharePointAccessInfo"/> class.
 /// </summary>
 /// <param name="webUrl">The web URL.</param>
 /// <param name="authenticationResult">The authentication result.</param>
 public SharePointAccessInfo(string webUrl, AuthenticationResult authenticationResult)
     : this(webUrl)
 {
     // Dont expose the refresh token on the client side!
     AccessToken = authenticationResult.AccessToken;
     ExpiresOn = authenticationResult.ExpiresOn;
     TenantId = authenticationResult.TenantId;
     UserId = authenticationResult.UserInfo.UniqueId;
     RefreshToken = authenticationResult.RefreshToken;
     UserEmail = authenticationResult.UserInfo.DisplayableId;
     User = new SharePointUser();
 }
        internal void Initialize(OriginalAuthenticationResult authResult)
        {
            AccessToken     = authResult.AccessToken;
            AccessTokenType = authResult.AccessTokenType;
            ExpiresOn       = authResult.ExpiresOn;
            IdToken         = authResult.IdToken;
            TenantId        = authResult.TenantId;
            UserInfo        = UserInfo.From(authResult.UserInfo);

            Status = (int)AuthenticationStatus.Success;

            ReplaceNullStringPropertiesWithEmptyString();
        }
  public static void CacheAuthenticationResult(AuthenticationResult authenticationResult) {
    session["UserHasAuthenticated"] = "true";
    // cache user authentication info
    session["tenant_id"] = authenticationResult.TenantId;
    session["user_id"] = authenticationResult.UserInfo.UniqueId;
    session["user_name"] = authenticationResult.UserInfo.GivenName + " " +
                           authenticationResult.UserInfo.FamilyName;
    // cache security tokens
    session["id_token"] = authenticationResult.IdToken;
    session["access_token"] = authenticationResult.AccessToken;
    session["refresh_token"] = authenticationResult.RefreshToken;

  }
 private AuthenticationResult Convert(ADALAuthenticationResult authenticationResult)
 {
     return(new AuthenticationResult()
     {
         Status = Convert(authenticationResult.Status),
         AccessToken = authenticationResult.AccessToken,
         Error = authenticationResult.Error,
         ErrorDescription = authenticationResult.ErrorDescription,
         UserFamilyName = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.FamilyName,
         UserGivenName = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.GivenName,
         UserDisplayableId = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.DisplayableId
     });
 }
            public Result(ActiveDirectory.AuthenticationResult result)
            {
                if (result is null)
                {
                    throw new ArgumentNullException(nameof(result));
                }

                _result            = result;
                _resultAccessToken = result.AccessToken;
                _resultAuthority   = result.Authority;
                _resultTenantId    = result.TenantId;
                _resultTokenType   = result.AccessTokenType;
            }
 public async Task<bool> Logout()
 {
     await Task.Factory.StartNew(async () =>
         { 
             var success = await _Authenticator.DeAuthenticate(_TenantAuthority);
             if (!success)
             {
                 throw new Exception("Failed to DeAuthenticate!");
             }
             _AuthenticationResult = null;
         });
     return true;
 }
 private AuthenticationResult Convert(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult)
 {
     return(new AuthenticationResult()
     {
         Status = AuthenticationStatus.Success, //only get Success or Exception from authentication
         AccessToken = authenticationResult.AccessToken,
         Error = null,
         ErrorDescription = null,
         UserFamilyName = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.FamilyName,
         UserGivenName = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.GivenName,
         UserDisplayableId = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.DisplayableId
     });
 }
Esempio n. 29
0
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId,
            Uri redirectUri,
            string extraQueryParameters)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (redirectUri is null)
            {
                throw new ArgumentNullException(nameof(redirectUri));
            }
            if (extraQueryParameters is null)
            {
                throw new ArgumentNullException(nameof(extraQueryParameters));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var platformParameters    = new ActiveDirectory.PlatformParameters(ActiveDirectory.PromptBehavior.SelectAccount);
                var userIdentifier        = ActiveDirectory.UserIdentifier.AnyUser;

                ActiveDirectory.AuthenticationResult result = await authenticationContext.AcquireTokenAsync(resource,
                                                                                                            clientId,
                                                                                                            redirectUri,
                                                                                                            platformParameters,
                                                                                                            userIdentifier,
                                                                                                            extraQueryParameters);

                return(new Result(result));
            }
            // We should just be able to catch AdalException here but due to an ADAL bug an HttpRequestException can be leaked:
            // https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1285
            // Until we update to ADAL 4.x or MSAL, we should just workaround this problem.
            catch (Exception exception)
            {
                throw new AuthenticationException(exception);
            }
        }
Esempio n. 30
0
 public static async Task<string> GetDrivesApiCallForSelectedFile( this SharePointOnlineUri fileHandlerFileGetOrPutUri, AuthenticationResult SharepointAdalAuthResult )
 {
    Guid fileHandlerFileId;
    System.Text.RegularExpressions.Regex findGuid = new System.Text.RegularExpressions.Regex( ".+/files/(?<fileGuid>[A-Fa-f0-9]+)/.*" );
    var match = findGuid.Match( fileHandlerFileGetOrPutUri.PathAndQuery ).Groups["fileGuid"].Value;
    if ( Guid.TryParse( match, out fileHandlerFileId ) )
    {
       return await GetDrivesApiCallForSelectedFile( fileHandlerFileGetOrPutUri, fileHandlerFileId, SharepointAdalAuthResult );
    }
    else
    {
       throw new ArgumentException( "Could not locate a GUID in the fileGetOrPutUri" );
    }
 }
        /// <summary>
        /// Create an application token provider that can retrieve tokens for the given application from the given context, using the given audience 
        /// and credential.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="context">The authentication context to use when retrieving tokens.</param>
        /// <param name="tokenAudience">The token audience to use when retrieving tokens.</param>
        /// <param name="credential">The client credential for this application.</param>
        /// <param name="authenticationResult">The token details provided when authenticating with the client credentials.</param>
        public ApplicationTokenProvider(AuthenticationContext context, string tokenAudience, ClientCredential credential, AuthenticationResult authenticationResult)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            if (authenticationResult == null)
            {
                throw new ArgumentNullException("authenticationResult");
            }

            Initialize(context, tokenAudience, credential.ClientId, new MemoryApplicationAuthenticationProvider(credential), authenticationResult, authenticationResult.ExpiresOn);
        }
Esempio n. 32
0
        /// <summary>
        /// Get a Microsoft Graph access token from Azure AD V1.
        /// </summary>
        /// <returns>An oauth2 access token.</returns>
        internal static async Task <string> AuthenticateAdalUserAsync()
        {
            ADAL.AuthenticationResult authenticationResult = null;
            try
            {
                authenticationResult = await _azureAdContext.AcquireTokenSilentAsync(_resourceUri, _appClientId);
            }
            catch (Exception)
            {
                authenticationResult = await _azureAdContext.AcquireTokenAsync(_resourceUri, _appClientId, new Uri(DefaultRedirectUri), new ADAL.PlatformParameters(ADAL.PromptBehavior.RefreshSession, false));
            }

            return(authenticationResult.AccessToken);
        }
        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // good code
            // Acquire a Token for the Graph API and cache it.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
            string userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);

            AuthenticationContext authContext = new AuthenticationContext(authority, new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache(Encoding.Default.GetBytes(userObjectId)));

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCodeAsync(
                notification.Code, new Uri(notification.RedirectUri), clientCred, GraphResourceId).Result;
            // decode token
            // https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens


            idToken     = authResult.IdToken;
            accessToken = authResult.AccessToken;

            return(Task.FromResult(0));


            //string authorizationCode = notification.Code;
            //ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

            //AuthenticationResult tokenResult = notification.(authorizationCode, new Uri(notification.RedirectUri), clientCred);
            //return Task.FromResult(0);

            /*
             * var code = notification.Code;
             * string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
             *
             * Microsoft.Identity.Client.TokenCache userTokenCache = new SessionTokenCache(
             *  signedInUserID,
             *  notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
             *
             *
             * ConfidentialClientApplication cca = new ConfidentialClientApplicationBuilder(
             *  clientId,
             *  redirectUri,
             *  new Microsoft.Identity.Client.ClientCredential(clientSecret),
             *  userTokenCache,
             *  null);
             * string[] scopes = graphScopes.Split(new char[] { ' ' });
             *
             * Microsoft.Identity.Client.AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
             * return Task.FromResult(0);
             */
        }
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId,
            Uri redirectUri,
            string extraQueryParameters)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (redirectUri is null)
            {
                throw new ArgumentNullException(nameof(redirectUri));
            }
            if (extraQueryParameters is null)
            {
                throw new ArgumentNullException(nameof(extraQueryParameters));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var platformParameters    = new ActiveDirectory.PlatformParameters(ActiveDirectory.PromptBehavior.SelectAccount);
                var userIdentifier        = ActiveDirectory.UserIdentifier.AnyUser;

                ActiveDirectory.AuthenticationResult result = await authenticationContext.AcquireTokenAsync(resource,
                                                                                                            clientId,
                                                                                                            redirectUri,
                                                                                                            platformParameters,
                                                                                                            userIdentifier,
                                                                                                            extraQueryParameters);

                return(new Result(result));
            }
            catch (ActiveDirectory.AdalException exception)
            {
                throw new AuthenticationException(exception);
            }
        }
Esempio n. 35
0
        public async Task GetAuthToken_Azure_Success()
        {
            using (var autoMock = AutoMock.GetLoose())
            {
                AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings();
                string resource = "https://test";

                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = autoMock.Mock <Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult>().Object;

                autoMock.Mock <AuthenticationContext>()
                .Setup(t => t.AcquireTokenSilentAsync(resource, authenticationSettings.ClientId))
                .Returns(() => Task.FromResult(result));

                await AzureADHelper.GetToken("userUniqueId", authenticationSettings, resource);
            }
        }
        protected override void PostTokenRequest(AuthenticationResult result)
        {
            base.PostTokenRequest(result);
            this.UniqueId = (result.UserInfo == null) ? null : result.UserInfo.UniqueId;
            this.DisplayableId = (result.UserInfo == null) ? null : result.UserInfo.DisplayableId;
            if (result.Resource != null)
            {
                this.Resource = result.Resource;
                Logger.Verbose(this.CallState, "Resource value in the token response was used for storing tokens in the cache");
            }

            // If resource is not passed as an argument and is not returned by STS either, 
            // we cannot store the token in the cache with null resource.
            // TODO: Store refresh token though if STS supports MRRT.
            this.StoreToCache = this.StoreToCache && (this.Resource != null);
        }
        /// <summary>
        /// Create an application token provider that can retrieve tokens for the given application from the given context, using the given audience 
        /// and certificate.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="context">The authentication context to use when retrieving tokens.</param>
        /// <param name="tokenAudience">The token audience to use when retrieving tokens.</param>
        /// <param name="certificate">The certificate associated with Active Directory application.</param>
        /// <param name="authenticationResult">The token details provided when authenticating with the client credentials.</param>
        public ApplicationTokenProvider(AuthenticationContext context, string tokenAudience, ClientAssertionCertificate certificate, AuthenticationResult authenticationResult)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            if (authenticationResult == null)
            {
                throw new ArgumentNullException("authenticationResult");
            }

            Initialize(context, tokenAudience, certificate.ClientId, 
                new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)),
                authenticationResult, authenticationResult.ExpiresOn);
        }
Esempio n. 38
0
        //Once we have an AuthenticationResult, get user information.
        private void PopulateCurrentUserInformation(AuthenticationResult result)
        {
            var rl = ResourceLoader.GetForCurrentView();
            AuthenticationHelper._settings.Values["TenantId"] = result.TenantId;
            AuthenticationHelper._settings.Values["LastAuthority"] = AuthenticationHelper._authenticationContext.Authority;

            _displayName = result.UserInfo.GivenName;
            _mailAddress = result.UserInfo.DisplayableId;
            EmailAddressBox.Text = _mailAddress;
            WelcomeText.Text = "Hi " + _displayName + ". " + rl.GetString("WelcomeMessage");
            MailButton.IsEnabled = true;
            EmailAddressBox.IsEnabled = true;
            _userLoggedIn = true;
            ProgressBar.Visibility = Visibility.Collapsed;
            ConnectButton.Content = "disconnect";
 
        }
        /// <summary>
        /// Refreshes the token used to access azure automation.
        /// This is currently called from a timer that runs on the Constants.tokenRefreshInterval
        /// If it is about to expire (2 minutes from the next refresh, it will renew)
        /// </summary>
        public void RefreshAutomationClientwithNewToken()
        {
            // Get the token for the tenant on this subscription and check if it is about to expire.
            // If it is, refresh it if possible.
            if (currSubscription == null) return;
            if (azureARMAuthResult.ExpiresOn.ToLocalTime() < DateTime.Now.AddMinutes(Constants.tokenRefreshInterval + 2))
            {
                azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.ActiveDirectoryTenantId);
                subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

                automationManagementClient = new AutomationManagementClient(subscriptionCreds);

                // Add user agent string to indicate this is coming from the ISE automation client.
                ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
                automationManagementClient.UserAgent.Add(ISEClientAgent);
            }
        }
Esempio n. 40
0
        protected void Page_Load(object sender, EventArgs e)
        {

            //Test for AuthenticationResult
            if (Session["authResult"] != null)
            {
                //Get the authentication result from the session
                authResult = (AuthenticationResult)Session["authResult"];

                //Show Power BI Panel
                signInStatus.Visible = true;

                //Set user and token from authentication result
                userLabel.Text = authResult.UserInfo.DisplayableId;
                accessTokenTextbox.Text = authResult.AccessToken;
            }
        }
        // Gets an access token. First tries to get the access token from the token cache.
        // This app uses a password (secret) to authenticate. Production apps should use a certificate.
        //public async Task<string> GetAppAccessTokenAsync()
        //{
        //    try
        //    {
        //        // For development mode purposes only. Production apps should use a client certificate.

        //        return await GetUserAccessTokenAsync(_tenantId);
        //    }
        //    catch (AdalException ex)
        //    {
        //        throw ex;
        //    }
        //}


        // TODO: Once the new method above has been fully tested, deprecate the cmmented code below:
        // Gets an access token. First tries to get the access token from the token cache.
        // This app uses a password (secret) to authenticate. Production apps should use a certificate.
        public async Task <string> GetAppAccessTokenAsync()
        {
            AuthenticationContext authContext = new AuthenticationContext($"{ _aadInstance }{ _tenantId }", null);

            try
            {
                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = await authContext.AcquireTokenAsync(
                    _graphResourceId,
                    new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_appId, _appSecret)); // For development mode purposes only. Production apps should use a client certificate.

                return(authResult.AccessToken);
            }
            catch (AdalException ex)
            {
                throw ex;
            }
        }
Esempio n. 42
0
        public async Task<bool> AuthenticateAsync()
        {
            await GetConfigAsync();

            // prompts the user for authentication
            _AuthenticationResult = await _Authenticator.Authenticate(_TenantAuthority, _ResourceUri, _AzureAuthenticationClientId, _ReturnUri);

            var accessToken = await GetTokenAsync();

            // instantiate an ActiveDirectoryClient to query the Graph API
            var activeDirectoryGraphApiClient = new ActiveDirectoryClient(
                new Uri(new Uri(_ResourceUri), _AzureGraphApiClientId),
                () => Task.FromResult<string>(accessToken)
            );

            return true;
        }
        // GET api/GetToken
        // This routine creates AzureAd token, another routine creates jwtBearer depending on which works with dual auth with cookies
        public async Task <HttpResponseMessage> Get()
        {
            // OWIN middleware validated the audience and issuer, but the scope must also be validated; must contain "access_as_user".
            string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' ');
            if (addinScopes.Contains("access_as_user"))
            {
                var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;
                Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion userAssertion = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion(bootstrapContext.Token);

                authContextADAL = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, new FileCache());
                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result     = null;
                Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential     clientCred =
                    new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientIdAddin, PasswordAddin);
                result = await authContextADAL.AcquireTokenAsync(enterpriseAppResourceId, clientCred, userAssertion);

                HttpResponseMessage response = null;

                try
                {
                    //response = ODataHelper.SendRequestWithAccessToken(enterpriseAppBaseAddress + "api/branches", result.AccessToken);
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);

                    // Call the To Do list service.
                    // Or call to /api/outlook/branches/user
                    response = await httpClient.GetAsync(enterpriseAppBaseAddress + "api/branches/user");

                    if (response.IsSuccessStatusCode)
                    {
                        return(response);
                    }
                    else
                    {
                        string failureDescription = await response.Content.ReadAsStringAsync();

                        return(SendErrorToClient(HttpStatusCode.Unauthorized, null, $"{response.ReasonPhrase}\n {failureDescription} " + "- An error occurred while getting /api/branches"));
                    }
                }
                catch (MsalServiceException e)
                {
                    itemNames.Add("e.Message: " + e.Message);
                }
            }
            // The token from the client does not have "access_as_user" permission.
            return(SendErrorToClient(HttpStatusCode.Unauthorized, null, "Missing access_as_user."));
        }
        public async Task <Models.Message> GetChannelMessages(string messageId)
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult res = await _authContext.AcquireTokenAsync("https://graph.microsoft.com", _credential);

            string accessToken = res.AccessToken;
            var    req         = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"https://graph.microsoft.com/beta/teams/{_teamsId}/channels/{_channelId}/messages/{messageId}"),
            };

            req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var reqRes = await _httpClient.SendAsync(req);

            string message = await reqRes.Content.ReadAsStringAsync();

            Models.Message retContent = JsonSerializer.Deserialize <Models.Message>(message);
            return(retContent);
        }
Esempio n. 45
0
        /// <summary>
        /// Fired when the user authenticates
        /// </summary>
        /// <param name="notification"></param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Get the user's object id (used to name the token cache)
            string userObjId = notification.AuthenticationTicket.Identity.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;

            // Create a token cache
            HttpContextBase   httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName);
            SessionTokenCache tokenCache  = new SessionTokenCache(userObjId, httpContext);

            // Exchange the auth code for a token
            ADAL.ClientCredential clientCred = new ADAL.ClientCredential(Settings.AAD_APP_ID, Settings.AAD_APP_SECRET);

            // Create the auth context
            ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext(
                string.Format(CultureInfo.InvariantCulture, Settings.AAD_INSTANCE, "common", ""), false, tokenCache);

            ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                notification.Code, notification.Request.Uri, clientCred, Settings.GRAPH_API_URL);
        }
        private async Task <AuthenticationResult> AcquireTokenSilentAsyncInternal(string resourceUrl, string clientId,
                                                                                  UserIdentifier userIdentifier)
        {
            OriginalAuthenticationResult authResult = null;
            AuthenticationResult         result;

            try
            {
                authResult = await _context.AcquireTokenSilentAsync(resourceUrl, clientId, userIdentifier.GetOriginalUserIdentifier());

                result = AuthenticationResult.From(authResult);
            }
            catch (Exception ex)
            {
                result = new AuthenticationResult(ex);
            }

            return(result);
        }
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Get the user's object id (used to name the token cache)
            string userObjId = notification.AuthenticationTicket.Identity
                               .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // Create a token cache
            HttpContextBase   httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName);
            SessionTokenCache tokenCache  = new SessionTokenCache(userObjId, httpContext);

            // Exchange the auth code for a token
            ADAL.ClientCredential clientCred = new ADAL.ClientCredential(appId, appSecret);

            // Create the auth context
            ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext(
                authority, false, tokenCache);

            ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                notification.Code, notification.Request.Uri, clientCred, "https://graph.microsoft.com");
        }
Esempio n. 48
0
        public void EnsureAuthenticationContext(String authority)
        {
            if (this.AuthenticationContext == null)
            {
                this.AuthenticationContext = new AuthenticationContext(authority);

                var tokenCacheItem = AuthenticationContext.TokenCache.ReadItems().FirstOrDefault();

                if (tokenCacheItem != null)
                {
                    this.AuthenticationContext = new AuthenticationContext(tokenCacheItem.Authority);
                }
            }

            this.AuthenticationResult =
                this.AuthenticationContext.AcquireToken(
                    Office365ServicesUris.AADGraphAPIResourceId,
                    ClientId,
                    new Uri(RedirectUri));
        }
        // GET: Accounts
        public ActionResult Index()
        {
            // TODO Substitute your correct CRM root service address, 
            string resource = "https://demogold.crm.dynamics.com";

            // TODO Substitute your app registration values that can be obtained after you
            // register the app in Active Directory on the Microsoft Azure portal.
            string clientId = "c447dac5-f9bc-4ca2-bc0f-4d8c649583f9";
            string redirectUrl = "https://localhost:44300/";


            // Authenticate the registered application with Azure Active Directory.
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
            _AuthenticationResult = authContext.AcquireToken(resource, clientId, new Uri(redirectUrl));

            //using this page: https://github.com/jlattimer/CrmWebApiCSharp/blob/master/CrmWebApiCSharp/Program.cs
            Task.WaitAll(Task.Run(async () => await GetAccounts()));

            return View(_jAccounts);
        }
Esempio n. 50
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        internal TokenCacheItem(TokenCacheKey key, AuthenticationResult result)
        {
            this.Authority = key.Authority;
            this.Resource = key.Resource;
            this.ClientId = key.ClientId;
            this.TokenSubjectType = key.TokenSubjectType;
            this.UniqueId = key.UniqueId;
            this.DisplayableId = key.DisplayableId;
            this.TenantId = result.TenantId;
            this.ExpiresOn = result.ExpiresOn;
            this.AccessToken = result.AccessToken;
            this.IdToken = result.IdToken;

            if (result.UserInfo != null)
            {
                this.FamilyName = result.UserInfo.FamilyName;
                this.GivenName = result.UserInfo.GivenName;
                this.IdentityProvider = result.UserInfo.IdentityProvider;
            }
        }
Esempio n. 51
0
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button>(Resource.Id.MyButton);

			button.Click += async (sender, args) =>
			{
				var authContext = new AuthenticationContext(commonAuthority);
				var cacheItems = authContext.TokenCache.ReadItems();
				if (authContext.TokenCache.ReadItems().Count() > 0)
					authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
				authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new PlatformParameters(this));
			};
		}
        private async Task <AuthenticationResult> AcquireTokenAsyncInternal(string resourceUrl, string clientId,
                                                                            Uri redirectUrl, int promptBehavior, UserIdentifier userIdentifier, string extraQueryParameters)
        {
            OriginalAuthenticationResult authResult = null;
            AuthenticationResult         result;

            var platformParameters = new PlatformParameters(PromptBehavior.IntToEnum(promptBehavior), UseCorporateNetwork);

            try
            {
                authResult = await _context.AcquireTokenAsync(resourceUrl, clientId, redirectUrl, platformParameters, userIdentifier.GetOriginalUserIdentifier(), extraQueryParameters);

                result = AuthenticationResult.From(authResult);
            }
            catch (Exception ex)
            {
                result = new AuthenticationResult(ex);
            }

            return(result);
        }
Esempio n. 53
0
        public ActionResult AppOnlyAccessToken()
        {
            string urlTokenEndpointForTenant =
                string.Format("https://login.windows.net/{0}/oauth2/token",
                              CustomAuthenticationManager.GetTenantID());

            ADAL.AuthenticationContext authenticationContext
                = new ADAL.AuthenticationContext(urlTokenEndpointForTenant);

            string resource = DemoConstants.TargetResource;

            ADAL.ClientAssertionCertificate clientAssertionCertificate =
                DemoConstants.GetClientAssertionCertificate();

            ADAL.AuthenticationResult authenticationResult =
                authenticationContext.AcquireToken(resource, clientAssertionCertificate);

            string           appOnlyAccessToken    = authenticationResult.AccessToken;
            JwtSecurityToken jwtAppOnlyAccessToken = new JwtSecurityToken(appOnlyAccessToken);

            return(View(jwtAppOnlyAccessToken));
        }
Esempio n. 54
0
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var userCredential        = new ActiveDirectory.UserCredential();

                ActiveDirectory.AuthenticationResult result = await AdalExtentions.AcquireTokenAsync(authenticationContext,
                                                                                                     resource,
                                                                                                     clientId,
                                                                                                     userCredential);

                return(new Result(result));
            }
            // We should just be able to catch AdalException here but due to an ADAL bug an HttpRequestException can be leaked:
            // https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1285
            // Until we update to ADAL 4.x or MSAL, we should just workaround this problem.
            catch (Exception exception)
            {
                throw new AuthenticationException(exception);
            }
        }
        public async Task <SubscriptionResponse> SetSubscription()
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult res = await _authContext.AcquireTokenAsync("https://graph.microsoft.com", _credential);

            string accessToken = res.AccessToken;
            var    req         = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"https://graph.microsoft.com/beta/subscriptions"),
            };

            req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var subscriptionSettting = new SubscriptionPost
            {
                ChangeType         = "created,updated",
                NotificationUrl    = _subscriptionUrl,
                ExpirationDateTime = DateTime.Now.AddMinutes(30),
                Resource           = $"/teams/{_teamsId}/channels/{_channelId}/messages"
            };
            string        json    = JsonSerializer.ToJsonString <SubscriptionPost>(subscriptionSettting);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            req.Content = content;

            var reqRes = await _httpClient.SendAsync(req);

            if (reqRes.IsSuccessStatusCode)
            {
                string contentString = await reqRes.Content.ReadAsStringAsync();

                SubscriptionResponse retContent = JsonSerializer.Deserialize <SubscriptionResponse>(contentString);
                return(retContent);
            }
            else
            {
                throw new Exception("Failed Post Message");
            }
        }
Esempio n. 56
0
        protected virtual Task PostRunAsync(AuthenticationResult result)
        {
            LogReturnedToken(result);

            return(CompletedTask);
        }
Esempio n. 57
0
        public static async Task <string> FetchTokenAsync()
        {
            /*In case of using different profiles (AAD users) from one client
             *      1. After Authentication during acquiring token, User Id shoud be recorded and saved
             *      2. UserIdentifier should be created using previously saved UserId, as a hint for context, when acquiring token again
             *          e.g.: UserIdentifier userId = new UserIdentifier(PBIConfig.Profile, UserIdentifierType.UniqueId);
             *      3. If you want to add new profile (user), than "Prompt Behavior" platform parameter should be set to "Always"
             *          a. in this case, the newly returned client id should be recorded again, and used as context information...
             */

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null;

            // first, try to get a token silently
            try
            {
                switch (PBIConfig.AuthMode)
                {
                case "Secret":
                    result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(PBIConfig.ClientId, PBIConfig.ClientSecret));

                    break;

                case "ClientId":
                    result = await AuthContext.AcquireTokenSilentAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId);

                    break;

                case "UserName":
                    result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId, new UserCredential(PBIConfig.UserName));

                    break;
                }
            }
            catch (AdalException adalException)
            {
                // There is no token in the cache; prompt the user to sign-in.
                if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently ||
                    adalException.ErrorCode == AdalError.InteractionRequired)
                {
                    try
                    {
                        result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId, new Uri(PBIConfig.RedirectUrl), new PlatformParameters(PromptBehavior.Auto));
                    }
                    catch (Exception e)
                    {
                        //Log Exception
                    }
                }
                else
                {
                    //Log exception
                }

                // An unexpected error occurred.
                //                ShowError(adalException);
            }
            catch (Exception e)
            {
                //Log Exception
            }

            return(result.AccessToken);
        }
        // GET: /<controller>/
        public async Task <ActionResult> Index()
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null;

            try
            {
                //string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(authority);
                ClientCredential      credential  = new ClientCredential(clientId, appKey);
//#if ASPNET50
//				result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, new Uri("http://localhost:42023"), null);
//#endif
                result = await authContext.AcquireTokenAsync(todoListResourceId, credential);

                //
                // Retrieve the user's To Do List.
                //
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "/api/todolist");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                //
                // Return the To Do List in the view.
                //
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    ViewBag.Message = "Success";
                    ViewBag.Content = responseContent;
                    return(View());
                }
                else
                {
                    ViewBag.Message = "Failure";

                    //
                    // If the call failed with access denied, then drop the current access token from the cache,
                    //     and show the user an error indicating they might need to sign-in again.
                    //
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == todoListResourceId);
                        foreach (TokenCacheItem tci in todoTokens)
                        {
                            authContext.TokenCache.DeleteItem(tci);
                        }

                        ViewBag.ErrorMessage = "UnexpectedError";
                        return(View());
                    }
                }
            }
            catch (Exception ee)
            {
                ViewBag.Message = ee.Message + ee.InnerException;
                //ViewBag.Message = "AuthorizationRequired";
                return(View());
            }


            //
            // If the call failed for any other reason, show the user an error.
            //
            return(View("Error"));
        }
Esempio n. 59
0
        private static async Task <string> GetToken()
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await context.AcquireTokenAsync(resource, credential);

            return(result.AccessToken);
        }
Esempio n. 60
0
 public void AddAccessToken(Uri orgUri, Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult accessToken)
 {
     // Access tokens can be matched on the hostname,
     // different endpoints in the same organization can use the same access token
     accessTokens[orgUri.Host] = accessToken;
 }