private static bool AuthenticateUser(string userName, string password) { string tenantName = ""; try { var parts = userName.Split('\\'); if (parts.Length > 1) { tenantName = parts[0]; userName = parts[1]; } else { throw new AuthenticationException("Could not determine tenant name and user name") { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "Could not determine tenant name and user name" }; } _oauth2AuthenticationSettings.Password = password; _oauth2AuthenticationSettings.Username = userName; _oauth2AuthenticationSettings.TenantName = tenantName; //Get Token for this user. var accessTokenResponse = BearerTokenHelper.RetrieveBearTokenFromCacheOrNew(_oauth2AuthenticationSettings); if (accessTokenResponse == null || string.IsNullOrEmpty(accessTokenResponse.AccessToken)) { throw new AuthenticationException("Unable to retrieve token") { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "Unable to retrieve token" }; } //If token was cached we did not guarantee that tenant, user name and password are correct. //We only verified that the tenant and user name are the same. var memoryCachingService = new MemoryCacheProvider(); var hashedPassword = memoryCachingService.FetchAndCache(accessTokenResponse.AccessToken, () => EncryptionHelper.Md5Encryption.GetMd5Hash(password), SecurityTokenConstants.TokenLifeTime); if (EncryptionHelper.Md5Encryption.GetMd5Hash(password) != hashedPassword) { throw new AuthenticationException("username or password does not match") { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "username or password does not match" } } ; //Validates that the token is good. ClaimsWebApiHelper.Authenticate(_oauth2AuthenticationSettings.Url, accessTokenResponse.AccessToken); } catch (Exception ex) { _logger.WriteLogEntry(tenantName, null, MethodBase.GetCurrentMethod().Name + " " + ex.GetInnerMostException(), LogLevelType.Error, ex); throw; } return(true); }
/// <summary> /// Retrieves the bearer token from cache or gets a new token. /// </summary> /// <param name="authenticationSettings">The authentication settings.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// authenticationSettings.ClientId /// or /// authenticationSettings.ClientSecret /// or /// authenticationSettings.Url /// or /// authenticationSettings.Password /// or /// authenticationSettings.Username /// or /// authenticationSettings.TenantName /// </exception> public static AccessTokenResponse RetrieveBearTokenFromCacheOrNew(Oauth2AuthenticationSettings authenticationSettings) { if (string.IsNullOrEmpty(authenticationSettings.ClientId)) { throw new ArgumentNullException("authenticationSettings.ClientId"); } if (string.IsNullOrEmpty(authenticationSettings.ClientSecret)) { throw new ArgumentNullException("authenticationSettings.ClientSecret"); } if (string.IsNullOrEmpty(authenticationSettings.Url)) { throw new ArgumentNullException("authenticationSettings.Url"); } if (string.IsNullOrEmpty(authenticationSettings.Password)) { throw new ArgumentNullException("authenticationSettings.Password"); } if (string.IsNullOrEmpty(authenticationSettings.Username)) { throw new ArgumentNullException("authenticationSettings.Username"); } if (string.IsNullOrEmpty(authenticationSettings.TenantName)) { throw new ArgumentNullException("authenticationSettings.TenantName"); } var oauthClient = new OAuth2Client(new Uri(authenticationSettings.Url + "token"), authenticationSettings.ClientId, authenticationSettings.ClientSecret); string key = string.Concat("AuthHash:", EncryptionHelper.Md5Encryption.GetMd5Hash(string.Concat(authenticationSettings.TenantName, authenticationSettings.Username))); //Cache Token in Memory var memoryCachingService = new MemoryCacheProvider(); var accessTokenResponse = memoryCachingService.FetchAndCache(key, () => oauthClient.RequestAccessTokenUserName(authenticationSettings.Username, authenticationSettings.Password, authenticationSettings.TenantName), SecurityTokenConstants.TokenLifeTime); //If token is within the threshold of expiring get refresh token. var timspan = accessTokenResponse.ExpiresOn - DateTime.Now; //if (accessTokenResponse.ExpiresOn >= DateTime.Now - SecurityTokenConstants.TokenLifeTimeEndOfLifeThreshold) if (timspan > new TimeSpan(0, 0, 0, 0) && timspan < SecurityTokenConstants.TokenLifeTimeEndOfLifeThreshold) { accessTokenResponse = RetrieveNewRefreshBearToken(authenticationSettings, accessTokenResponse.RefreshToken); } if (accessTokenResponse == null || accessTokenResponse.ExpiresOn <= DateTime.Now) { memoryCachingService.ClearCache(key); accessTokenResponse = memoryCachingService.FetchAndCache(key, () => oauthClient.RequestAccessTokenUserName(authenticationSettings.Username, authenticationSettings.Password, authenticationSettings.TenantName), SecurityTokenConstants.TokenLifeTime); return(accessTokenResponse); } return(accessTokenResponse); }