private async void Page_Loaded(object sender, RoutedEventArgs e) { var mailId = Convert.ToString(LocalStorage.GetSetting("mailId")); var name = Convert.ToString(LocalStorage.GetSetting("name")); if (!String.IsNullOrEmpty(mailId)) { authResult = await authContext.AcquireTokenSilentAsync("https://login.windows.net/appsthepagedot.onmicrosoft.com", clientId); if (authResult.Status == Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationStatus.ClientError) { var refreshToken = Convert.ToString(LocalStorage.GetSetting("refreshToken")); if (!String.IsNullOrEmpty(refreshToken)) { authResult = await authContext.AcquireTokenByRefreshTokenAsync(refreshToken, clientId); SaveTokenLocal(); } else { authContext.AcquireTokenAndContinue("https://graph.windows.net/", clientId, new Uri("http://www.google.de"), authenticationContextDelegate); } } loginButton.Visibility = Visibility.Collapsed; logoutButton.Visibility = Visibility.Visible; userName.Text = "Hallo, " + name; var accessToken = LocalStorage.GetSetting("accessToken"); } else { logoutButton.Visibility = Visibility.Collapsed; loginButton.Visibility = Visibility.Visible; } }
public static OAuth.AuthenticationResult ConvertAuthenticationResult(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache) { var result = new OAuth.AuthenticationResult { AccessToken = authResult.AccessToken, UserName = $"{authResult.UserInfo.GivenName} {authResult.UserInfo.FamilyName}", UserUniqueId = authResult.UserInfo.UniqueId, ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks, TokenCache = tokenCache.Serialize() }; return(result); }
public async Task <string> RefreshPhoto(string uniqueName) { var currentUniqueName = User.Claims.First(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; string name = uniqueName ?? currentUniqueName; string token; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await Utils.TokenManager.GetAccessToken(HttpContext); token = result.AccessToken; return(await StoreUserPhoto(name, token)); }
public async static System.Threading.Tasks.Task <string> GetToken(string authority, string resource, string scope) { var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await authContext.AcquireTokenAsync(resource, _clientCredential); if (result == null) { throw new System.InvalidOperationException("Failed to obtain the access token"); } return(result.AccessToken); }
private async Task <string> GetAppTokenAsync() { // *****ADAL code Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult tokenResult = null; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false); Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey); tokenResult = await authContext.AcquireTokenAsync(resAzureGraphAPI, credential); return(tokenResult.AccessToken); }
public static TokenResponse ConvertAuthenticationResultToTokenResponse(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult value) { return(new TokenResponse { token_type = value.AccessTokenType, expires_in = "", scope = "", expires_on = value.ExpiresOn.ToString(), not_before = "", resource = "", access_token = value.AccessToken, // refresh_token = value.RefreshToken, id_token = value.IdToken }); }
public static AuthResult FromADALAuthenticationResult(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache) { var result = new AuthResult { AccessToken = authResult.AccessToken, UserName = $"{authResult.UserInfo.GivenName} {authResult.UserInfo.FamilyName}", UserUniqueId = authResult.UserInfo.UniqueId, ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks, TokenCache = tokenCache.Serialize(), TenantId = authResult.TenantId, Upn = authResult.UserInfo.DisplayableId }; return(result); }
public static AuthResult FromADALAuthenticationResult(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache) { var TokenClaim = new System.IdentityModel.Tokens.JwtSecurityToken(authResult.IdToken); var alias = TokenClaim.Claims.FirstOrDefault(m => m.Type == "upn").Value; var result = new AuthResult { AccessToken = authResult.AccessToken, IdToken = authResult.IdToken, UserName = $"{authResult.UserInfo.GivenName} {authResult.UserInfo.FamilyName}", UserUniqueId = authResult.UserInfo.UniqueId, ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks, TokenCache = tokenCache.Serialize(), Alias = alias }; return result; }
public async Task <string> RefreshUserInfo(string uniqueName) { var currentUniqueName = User.Claims.First(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; if (uniqueName != currentUniqueName) { throw new InvalidOperationException("StoreUserInfo currently does not impersonate the user. It uses /me"); } string name = uniqueName ?? currentUniqueName; string token; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await Utils.TokenManager.GetAccessToken(HttpContext); token = result.AccessToken; return(await StoreUserInfo(name, token)); }
private async Task <string> getTokenAsync() { var tenantName = ConfigurationManager.AppSettings.Get("tenantName"); var aad = ConfigurationManager.AppSettings.Get("aad"); var authority = string.Format(CultureInfo.InvariantCulture, aad, tenantName); var clientId = ConfigurationManager.AppSettings.Get("clientId"); var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); X509Certificate2 cert = Helper.GetCertificateBySubject(); var certCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate(clientId, cert); string token = null; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await authContext.AcquireTokenAsync(_resource, certCred); if (result != null) { token = result.AccessToken; } return(token); }
// Get an authenticated Microsoft Graph Service client. public static GraphServiceClient GetAuthenticatedClient(string graphEndpoint) { GraphServiceClient graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async(requestMessage) => { //string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync(); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = await(SampleAuthProvider.Instance.GetOldUserAccessTokenAsync()); // Append the access token to the request. requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken); requestMessage.RequestUri = new Uri("https://graph.windows.net/" + ConfigurationManager.AppSettings["b2c:Tenant"] + "/" + graphEndpoint + "/ " + "?" + "api-version=1.6"); // Get event times in the current time zone. //requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\""); // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove. //requestMessage.Headers.Add("SampleID", "aspnet-snippets-sample"); })); return(graphClient); }
private void CheckAuthResultStatus(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult) { switch (authenticationResult.Status) { case Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationStatus.Success: SaveTokenLocal(); loginButton.Visibility = Visibility.Collapsed; logoutButton.Visibility = Visibility.Visible; userName.Text = "Hallo, " + authenticationResult.UserInfo.GivenName; break; case Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationStatus.ServiceError: App.ShowErrorDialog("Die Anmeldung am Server ist fehlgeschlagen. Überprüfen Sie Ihre Eingaben und versuchen Sie es erneut.", "Fehler"); break; case Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationStatus.ClientError: App.ShowErrorDialog("Die Anmeldung am Server ist fehlgeschlagen, da es einen Fehler in der Applikation gab. Bitte versuchen Sie die Anmeldung erneut.", "Fehler"); break; } }
private void Logout() { if (authContext != null && authContext.TokenCache != null) { authContext.TokenCache.Clear(); } if (authResult != null) { authResult = null; } LocalStorage.RemoveSetting("mailId"); LocalStorage.RemoveSetting("name"); LocalStorage.RemoveSetting("accessToken"); LocalStorage.RemoveSetting("refreshToken"); logoutButton.Visibility = Visibility.Collapsed; loginButton.Visibility = Visibility.Visible; userName.Text = "Nicht eigneloggt!"; }
private async void UserAuthentication_Click(object sender, RoutedEventArgs e) { string msg = string.Empty; int count = -1; string Token = null; LogMessage("Interactive User Authentication - Azure Tenant: " + azureActiveDirectoryTenantDomain.Text); string authority = "https://login.microsoftonline.com/" + azureActiveDirectoryTenantDomain.Text; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ac = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); string resourceUrl = "https://rest.media.azure.net"; string redirectUri = "https://AzureMediaServicesNativeSDK"; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; try { Microsoft.IdentityModel.Clients.ActiveDirectory.IPlatformParameters param = new Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior.Always, false);; result = await ac.AcquireTokenAsync(resourceUrl, "d476653d-842c-4f52-862d-397463ada5e7", new Uri(redirectUri), param); } catch (Exception ex) { LogMessage("Interactive User Authentication - Exception: " + ex.Message); } if (result != null) { Token = result.AccessToken; if (!string.IsNullOrEmpty(Token)) { LogMessage("Interactive User Authentication successful"); LogMessage("Token: " + Token); try { LogMessage("Getting Media Objects - Account Name: " + legacyAccountName.Text + " from region " + azureRegion.Text); count += await GetMediaObjectsCount <Asset>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <MediaProcessor>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <Channel>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <AzureMediaServicesREST.Program>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <StreamingEndpoint>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <Locator>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <AccessPolicie>(Token, legacyAccountName.Text, azureRegion.Text); SaveSettings(); } catch (Exception ex) { msg = ex.Message; LogMessage("Getting Media Objects - Exception: " + msg); } if (count >= 0) { Show("Interactive User Authentication successful: " + count.ToString() + " asset(s) found"); } else { Show("Interactive User Authentication failed" + (string.IsNullOrEmpty(msg) ? "" : ": Exception - " + msg)); } } else { Show("Interactive User Authentication failed"); } } else { Show("Interactive User Authentication failed"); } }
public async Task <IActionResult> Old() { var user = User.Claims.First(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; var userStatus = Util.ConnectToRemoteService <int>(HttpMethod.Get, Util.PermissionsURL + "api/useroperations/getuserstatus", user, string.Empty).Result; string token = null; ViewBag.User = user; ViewBag.UserStatus = userStatus; if (!Startup.IsSimpleAuthForDemo) { try { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await TokenManager.GetAccessToken(HttpContext); token = result.AccessToken; ViewBag.Token = token; if (userStatus == 0) { StoreUserInfo(user, token); } } catch (Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException) { return(Redirect("/Account/SignIn")); } } UsageTelemetry.Track(user, ArdaUsage.Dashboard_Index); return(View()); }
private void authenticationContextDelegate(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result) { authResult = result; CheckAuthResultStatus(authResult); }