public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string[] scopes) { var extraParameters = BuildExtraParameters(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(); Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication("https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0", AuthSettings.ClientId, redirectUri.ToString(), new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); //var uri = "https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0/authorize?response_type=code" + // "&client_id=" + AuthSettings.ClientId + // "&client_secret=" + AuthSettings.ClientSecret + // "&redirect_uri=" + HttpUtility.UrlEncode(AuthSettings.RedirectUrl) + // "&scope=" + HttpUtility.UrlEncode("openid profile " + string.Join(" ", scopes)) + // "&state=" + encodedCookie; var uri = await client.GetAuthorizationRequestUrlAsync( scopes, null, $"state={extraParameters}"); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { return(null); } return(null); }
public static async Task <AuthResult> GetToken(string userUniqueId, Microsoft.Identity.Client.TokenCache tokenCache, string[] scopes) { Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, AuthSettings.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); var result = await client.AcquireTokenSilentAsync(scopes, userUniqueId); AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache); return(authResult); }
public static async Task <AuthResult> GetTokenByAuthCodeAsync(string authorizationCode, Microsoft.Identity.Client.TokenCache tokenCache, string[] scopes) { Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, AuthSettings.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); var result = await client.AcquireTokenByAuthorizationCodeAsync(scopes, authorizationCode); AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache); return(authResult); }
public static async Task <AuthResult> GetTokenByAuthCodeAsync(string authorizationCode, Microsoft.Identity.Client.TokenCache tokenCache) { Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, AuthSettings.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); //Temporary workaround since the current experimental library is unable to decode the token in v2 //var result2 = await GetTokenFromAuthCodeAsyncV2(activeDirectoryEndpointUrl.Value, activeDirectoryTenant.Value, scopes.Value, clientId.Value, clientSecret.Value, authorizationCode, redirectUri.ToString()); var result = await client.AcquireTokenByAuthorizationCodeAsync(AuthSettings.Scopes, authorizationCode); AuthResult authResult = AuthResult.FromMSALAuthenticationResult(result, tokenCache); return(authResult); }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie) { var encodedCookie = UrlToken.Encode(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase)) { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant); var uri = await context.GetAuthorizationRequestUrlAsync( AuthSettings.ResourceId, AuthSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(); Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, redirectUri.ToString(), new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); var uri = await client.GetAuthorizationRequestUrlAsync( AuthSettings.Scopes, null, "state=" + encodedCookie); //, // null // clientId.Value, // redirectUri, // Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, // "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { return(null); } return(null); }
public async Task <string> GraphTest() { try { // The ClientCredential is where you pass in your client_id and client_secret, which are // provided to Azure AD in order to receive an access_token using the app's identity. var credential = new Microsoft.Identity.Client.ClientCredential(AppConfig.AzureAdOptions.ClientSecret); var cca = new Microsoft.Identity.Client.ConfidentialClientApplication( AppConfig.AzureAdOptions.ClientId, "https://login.microsoftonline.com/nekosoftbtgmail.onmicrosoft.com", $"{AppConfig.WebApplication.BaseUrl.TrimEnd('/')}/{AppConfig.AzureAdOptions.CallbackPath.TrimStart('/')}", credential, null, null); var scopes = "email User.Read User.ReadBasic.All Mail.Send" .Split(' ') .Select(t => ("https://graph.microsoft.com/" + t).ToLower()) .ToArray(); var result = cca.AcquireTokenForClientAsync(new[] { "https://graph.microsoft.com/.default" }).Result; //var result = cca.AcquireTokenForClientAsync(scopes).Result; does not work(?) var graphClient = new Microsoft.Graph.GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider( async requestMessage => { // Passing tenant ID to the sample auth provider to use as a cache key //var accessToken = await _authProvider.GetUserAccessTokenAsync(userId); // Append the access token to the request requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove. //requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample"); })); var userId = "d97257fc-15e8-4f06-8384-988e055f72ca"; try { // Load user profile. var users = await graphClient.Users.Request().GetAsync(); //var user = await graphClient.Users[userId].Request().GetAsync(); does not work(?) return(JsonConvert.SerializeObject(users, Formatting.Indented)); } catch (Microsoft.Graph.ServiceException e) { switch (e.Error.Code) { case "Request_ResourceNotFound": case "ResourceNotFound": case "ErrorItemNotFound": case "itemNotFound": return(JsonConvert.SerializeObject(new { Message = $"User '{userId}' was not found." }, Formatting.Indented)); case "ErrorInvalidUser": return(JsonConvert.SerializeObject(new { Message = $"The requested user '{userId}' is invalid." }, Formatting.Indented)); case "AuthenticationFailure": return(JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)); case "TokenNotFound": //await httpContext.ChallengeAsync(); return(JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)); default: return(JsonConvert.SerializeObject(new { Message = "An unknown error has occured." }, Formatting.Indented)); } } } catch (Exception ex) { throw ex; } }