/// <summary> /// Generates a shared access signature that can be used to authenticate with a topic. /// The signature can be used as the input to the <see cref="AzureSasCredential(string)"/> constructor. /// This credential can then be passed to the <see cref="EventGridPublisherClient(Uri, AzureSasCredential, EventGridPublisherClientOptions)"/> constructor. /// </summary> /// <param name="key">The <see cref="AzureKeyCredential"/> to use to authenticate with the service /// when generating the shared access signature.</param> /// <returns>A shared access signature that can be used to authenticate with an Event Grid topic.</returns> public string GenerateSas(AzureKeyCredential key) { Argument.AssertNotNull(key, nameof(key)); const char Resource = 'r'; const char Expiration = 'e'; const char Signature = 's'; var uriBuilder = new RequestUriBuilder(); uriBuilder.Reset(Endpoint); uriBuilder.AppendQuery("api-version", ApiVersion.GetVersionString(), true); string encodedResource = HttpUtility.UrlEncode(uriBuilder.ToString()); var encodedExpirationUtc = HttpUtility.UrlEncode(ExpiresOn.ToString(CultureInfo.CreateSpecificCulture("en-US"))); string unsignedSas = $"{Resource}={encodedResource}&{Expiration}={encodedExpirationUtc}"; using (var hmac = new HMACSHA256(Convert.FromBase64String(key.Key))) { string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(unsignedSas))); string encodedSignature = HttpUtility.UrlEncode(signature); string signedSas = $"{unsignedSas}&{Signature}={encodedSignature}"; return(signedSas); } }
/// <summary> /// To the JWT dictionary. /// </summary> /// <returns></returns> public Dictionary <string, object> ToJwtDictionary() { return(new Dictionary <string, object>() { { "userId", UserId.ToString() }, { "initOn", InitOn.ToString("yyyyMMddHHmmss") }, { "expiresOn", ExpiresOn.ToString("yyyyMMddHHmmss") } }); }
/// <summary> /// Convert to driver's internal token class. /// </summary> internal SqlFedAuthToken ToSqlFedAuthToken() { var tokenBytes = AccessTokenBytesFromString(AccessToken); return(new SqlFedAuthToken { accessToken = tokenBytes, dataLen = (uint)tokenBytes.Length, expirationFileTime = ExpiresOn.ToFileTime() }); }
public EmbedBuilder ToEmbedBuilder(DiscordSocketClient client) { var guild = client?.GetGuild(GuildId); var moderator = guild?.GetUser(ModeratorId); var builder = new EmbedBuilder(); bool isTemporary = this.IsTempCase(); builder.AddField("Type:", CaseType.ToString(), true); if (moderator != null) { builder.AddField("Admin:", moderator.Username, true); } builder.AddField("Created:", CreatedOn.ToLocalTime().ValueToString(), true); builder.AddField("Expires:", isTemporary ? ExpiresOn.ToLocalTime().ValueToString() : "-", true); builder.AddField("Reason:", Reason); return(builder); }
/// <summary> /// Builds up the UserDelegationKey portion of the SAS query parameter string. /// </summary> public void AppendProperties(StringBuilder stringBuilder) { if (!string.IsNullOrWhiteSpace(ObjectId)) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyObjectId, ObjectId); } if (!string.IsNullOrWhiteSpace(TenantId)) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyTenantId, TenantId); } if (StartsOn != DateTimeOffset.MinValue) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyStart, WebUtility.UrlEncode(StartsOn.ToString(Constants.SasTimeFormatSeconds, CultureInfo.InvariantCulture))); } if (ExpiresOn != DateTimeOffset.MinValue) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyExpiry, WebUtility.UrlEncode(ExpiresOn.ToString(Constants.SasTimeFormatSeconds, CultureInfo.InvariantCulture))); } if (!string.IsNullOrWhiteSpace(Service)) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyService, Service); } if (!string.IsNullOrWhiteSpace(Version)) { stringBuilder.AppendQueryParameter(Constants.Sas.Parameters.KeyVersion, Version); } }
/// <summary> /// Determines whether or the access is near expiration. /// </summary> /// <returns><c>true</c> if near expiration; otherwise <c>false</c>.</returns> public bool IsNearExpiry() { return(DateTime.UtcNow > ExpiresOn.AddMinutes(-1)); }
/// <summary> /// Update token if token has been expired. /// </summary> public void UpdateToken() { if (ExpiresOn > DateTime.UtcNow) { return; } Debug.WriteLine("Need new token"); lock (lockUpdateProcess) { Debug.WriteLine("Enter to critical section of getting token"); if (ExpiresOn <= DateTime.UtcNow && !IsProcessing) { Debug.WriteLine("Start getting token"); string newToken = null; Exception exception = null; try { if (_authenticationService != null) { IsProcessing = true; #if DEBUG //Thread.Sleep(3000); #endif //get url for scope authenticate var dataServicesBaseUri = new Uri(BaseUrl); // get new token newToken = _authenticationService.AuthenticateUser(UserName, Password, dataServicesBaseUri); Debug.WriteLine("Token updated"); if (!String.IsNullOrEmpty(newToken)) { // Parse token var swToken = Foundation.Security.Swt.SimpleWebToken.Parse(newToken); Token = newToken; ExpiresOn = swToken.ExpiresOn; ExpiresOn = ExpiresOn.AddMinutes(-(ExpiresOn - DateTime.UtcNow).TotalMinutes / 2); CurrentUserId = swToken.Claims.Where(x => x.Key == ClaimTypes.NameIdentifier) .Select(x => x.Value) .FirstOrDefault(); CurrentUserName = swToken.Claims.Where(x => x.Key == ClaimTypes.Name) .Select(x => x.Value) .FirstOrDefault(); var registrationType = swToken.Claims.Where(x => x.Key == SecurityClaims.AccountRegistrationType).Select(x => x.Value).FirstOrDefault(); if (!String.IsNullOrEmpty(registrationType)) { RegistrationType = (RegisterType)Enum.Parse(typeof(RegisterType), registrationType); } var permissions = swToken.Claims.Where(x => x.Key == SecurityClaims.AccountPermission) .Select(x => x.Value) .ToArray(); Permissions = permissions; } } } catch (Exception e) { exception = new GetTokenException(e.Message); } finally { IsProcessing = false; } if (exception == null && String.IsNullOrEmpty(newToken)) { exception = new GetTokenException(Resources.Login_or_password_is_incorrect); } if (exception != null) { throw exception; } } Debug.WriteLine("Exit from critical section of getting token"); } }