public static void CreateSha256HashTest()
 {
     ICryptographyHelper cryptoHelper = new CryptographyHelper();
     string hash = cryptoHelper.CreateSha256Hash("abc");
     string hash2 = cryptoHelper.CreateSha256Hash("abd");
     string hash3 = cryptoHelper.CreateSha256Hash("abc");
     Verify.AreEqual(hash, hash3);
     Verify.AreNotEqual(hash, hash2);
     Verify.AreEqual(hash, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=");
 }
Пример #2
0
        private void LogReturnedToken(AuthenticationResult result)
        {
            if (result.AccessToken != null)
            {
                string accessTokenHash = CryptographyHelper.CreateSha256Hash(result.AccessToken);

                CallState.Logger.Information(this.CallState,
                                             string.Format(CultureInfo.CurrentCulture,
                                                           "=== Token Acquisition finished successfully. An access token was retuned:\n\tAccess Token Hash: {0}\n\tExpiration Time: {1}\n\tUser Hash: {2}\n\t",
                                                           accessTokenHash,
                                                           result.ExpiresOn,
                                                           result.UserInfo != null
                            ? CryptographyHelper.CreateSha256Hash(result.UserInfo.UniqueId)
                            : "null"));
            }
        }
Пример #3
0
        public AcquireTokenOnBehalfHandler(RequestData requestData, UserAssertion userAssertion)
            : base(requestData)
        {
            if (userAssertion == null)
            {
                throw new ArgumentNullException("userAssertion");
            }

            this.userAssertion           = userAssertion;
            this.DisplayableId           = userAssertion.UserName;
            CacheQueryData.AssertionHash = CryptographyHelper.CreateSha256Hash(userAssertion.Assertion);

            CallState.Logger.Verbose(CallState,
                                     string.Format(CultureInfo.InvariantCulture,
                                                   "Username provided in user assertion - " + string.IsNullOrEmpty(this.DisplayableId)));
            this.SupportADFS = true;
        }
Пример #4
0
        private AuthenticationResultEx ResultFromBrokerResponse(IDictionary <string, string> responseDictionary)
        {
            TokenResponse response;

            if (responseDictionary.ContainsKey("error") || responseDictionary.ContainsKey("error_description"))
            {
                response = TokenResponse.CreateFromBrokerResponse(responseDictionary);
            }
            else
            {
                string expectedHash       = responseDictionary["hash"];
                string encryptedResponse  = responseDictionary["response"];
                string decryptedResponse  = BrokerKeyHelper.DecryptBrokerResponse(encryptedResponse);
                string responseActualHash = CryptographyHelper.CreateSha256Hash(decryptedResponse);
                byte[] rawHash            = Convert.FromBase64String(responseActualHash);
                string hash = BitConverter.ToString(rawHash);
                if (expectedHash.Equals(hash.Replace("-", "")))
                {
                    responseDictionary = EncodingHelper.ParseKeyValueList(decryptedResponse, '&', false, null);
                    response           = TokenResponse.CreateFromBrokerResponse(responseDictionary);
                }
                else
                {
                    response = new TokenResponse
                    {
                        Error            = AdalError.BrokerReponseHashMismatch,
                        ErrorDescription = AdalErrorMessage.BrokerReponseHashMismatch
                    };
                }
            }

            var dateTimeOffset = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));

            dateTimeOffset = dateTimeOffset.AddSeconds(response.ExpiresOn);
            return(response.GetResult(dateTimeOffset, dateTimeOffset));
        }
        protected override async Task PreRunAsync()
        {
            await base.PreRunAsync().ConfigureAwait(false);

            if (this.userCredential != null)
            {
                if (string.IsNullOrWhiteSpace(this.userCredential.UserName))
                {
                    this.userCredential.UserName = await platformInformation.GetUserPrincipalNameAsync().ConfigureAwait(false);

                    if (string.IsNullOrWhiteSpace(userCredential.UserName))
                    {
                        CallState.Logger.Information(this.CallState, "Could not find UPN for logged in user");
                        throw new AdalException(AdalError.UnknownUser);
                    }

                    CallState.Logger.Verbose(this.CallState, string.Format(CultureInfo.CurrentCulture, " Logged in user with hash '{0}' detected", CryptographyHelper.CreateSha256Hash(userCredential.UserName)));
                }

                this.DisplayableId = userCredential.UserName;
            }
            else if (this.userAssertion != null)
            {
                this.DisplayableId = userAssertion.UserName;
            }
        }
        protected override async Task PreTokenRequest()
        {
            await base.PreTokenRequest().ConfigureAwait(false);

            if (this.PerformUserRealmDiscovery())
            {
                UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState).ConfigureAwait(false);

                CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " User with hash '{0}' detected as '{1}'", CryptographyHelper.CreateSha256Hash(this.userCredential.UserName), userRealmResponse.AccountType));

                if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl))
                    {
                        throw new AdalException(AdalError.MissingFederationMetadataUrl);
                    }

                    WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState).ConfigureAwait(false);

                    CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl));

                    WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState, userRealmResponse.CloudAudienceUrn).ConfigureAwait(false);

                    CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType));

                    // We assume that if the response token type is not SAML 1.1, it is SAML 2
                    this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
                }
                else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // handle password grant flow for the managed user
                    if (this.userCredential.PasswordToCharArray() == null)
                    {
                        throw new AdalException(AdalError.PasswordRequiredForManagedUserError);
                    }
                }
                else
                {
                    throw new AdalException(AdalError.UnknownUserType);
                }
            }
        }