Esempio n. 1
0
        public async Task <Microsoft.Identity.Client.AuthenticationResult> GetAuthTokenAsync(
            string clientid,
            string tenantid,
            string[] scopes,
            string tokenfile,
            bool govcloud = false)
        {
            app = govcloud ? Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(clientid)
                  .WithAuthority(
                Microsoft.Identity.Client.AzureCloudInstance.AzureUsGovernment,
                tenantid)
                  .Build()
                            : Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(clientid)
                  .WithTenantId(tenantid)
                  .Build();
            SetSerialization(
                app.UserTokenCache,
                tokenfile);
            Microsoft.Identity.Client.AuthenticationResult result = await GetAuthTokenAsync(scopes);

            if ((result == null) && (govcloud))
            {
                app = Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(clientid)
                      .WithTenantId(tenantid)
                      .Build();
                SetSerialization(
                    app.UserTokenCache,
                    tokenfile);
                result = await GetAuthTokenAsync(scopes);
            }
            return(result);
        }
 /// <summary>
 /// Clears the authentication objects and cache data.
 /// </summary>
 public static void SignOut()
 {
     SoftmakeAll.SDK.Fluent.GeneralCacheHelper.Clear();
     SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.DisposeAsync().ConfigureAwait(false);
     SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials     = null;
     SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult    = null;
     SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = null;
 }
Esempio n. 3
0
        public XboxAuthentication(AuthenticationSettings authSettings, Microsoft.Identity.Client.AuthenticationResult microsoftAccount)
        {
            AuthSettings = authSettings;


            XboxLive = XboxLiveAuthenticate(microsoftAccount.AccessToken);
            XboxSecurityTokenService = XSTSAuthenticate(XboxLive.Token);
        }
Esempio n. 4
0
        public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.AuthenticationResult authResult, Microsoft.Identity.Client.TokenCache tokenCache)
        {
            var result = new AuthResult
            {
                AccessToken       = authResult.Token,
                UserName          = $"{authResult.User.Name}",
                UserUniqueId      = authResult.User.UniqueId,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache        = tokenCache.Serialize()
            };

            return(result);
        }
Esempio n. 5
0
 public static TokenResponse ConvertAuthenticationResultToTokenResponse(Microsoft.Identity.Client.AuthenticationResult value)
 {
     return(new TokenResponse
     {
         token_type = "",
         expires_in = "",
         scope = string.Join(",", value.Scopes),
         expires_on = value.ExpiresOn.ToString(),
         not_before = "",
         resource = "",
         access_token = value.AccessToken,
         // refresh_token = value.RefreshToken,
         id_token = value.IdToken
     });
 }
Esempio n. 6
0
        public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.AuthenticationResult authResult, Microsoft.Identity.Client.TokenCache tokenCache)
        {
            var TokenClaim = new System.IdentityModel.Tokens.JwtSecurityToken(authResult.IdToken);
            var alias = TokenClaim.Claims.FirstOrDefault(m => m.Type == "preferred_username").Value;

            var result = new AuthResult
            {
                AccessToken = authResult.Token,
                IdToken = authResult.IdToken,
                UserName = $"{authResult.User.Name}",
                UserUniqueId = authResult.User.UniqueId,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache = tokenCache.Serialize(),
                Alias = alias
            };

            return result;
        }
Esempio n. 7
0
 private void RefreshToken()
 {
     Microsoft.Identity.Client.AuthenticationResult authResult =
         msal.GetAuthTokenAsync(clientId,
                                tenantId,
                                accessScopes,
                                tokenFile
                                ).GetAwaiter()
         .GetResult();
     if (authResult != null)
     {
         httpClient.DefaultRequestHeaders.Authorization =
             new System.Net.Http.Headers.AuthenticationHeaderValue(
                 "Bearer",
                 authResult.AccessToken);
         accessToken        = authResult.AccessToken;
         accessTokenCreated = DateTime.UtcNow;
     }
 }
Esempio n. 8
0
        private async Task <Microsoft.Identity.Client.AuthenticationResult> GetAuthTokenAsync(
            IEnumerable <string> scopes)
        {
            Microsoft.Identity.Client.AuthenticationResult result = null;
            var accounts = await app.GetAccountsAsync();

            if (accounts.Any())
            {
                try
                {
                    result = await app.AcquireTokenSilent(
                        scopes,
                        accounts.FirstOrDefault()
                        ).ExecuteAsync();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            if (result == null)
            {
                try
                {
                    result = await app.AcquireTokenWithDeviceCode(
                        scopes,
                        deviceCodeResultCallback =>
                    {
                        Console.WriteLine(deviceCodeResultCallback.Message);
                        return(Task.FromResult(0));
                    }).ExecuteAsync();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(result);
        }
Esempio n. 9
0
 public Microsoft.SharePoint.Client.ClientContext GetClientContext(
     string clientid,
     string tenantid,
     string url,
     string[] scopes,
     string tokenfile)
 {
     try
     {
         Microsoft.Identity.Client.AuthenticationResult authResult =
             msal.GetAuthTokenAsync(clientid,
                                    tenantid,
                                    scopes,
                                    tokenfile
                                    ).GetAwaiter()
             .GetResult();
         return(GetClientContext(GetValidAccessToken(), url));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        /// <summary>
        /// Authenticate user/application using Credentials.
        /// </summary>
        /// <param name="Credentials">Credentials to use during authentication process.</param>
        public static async System.Threading.Tasks.Task AuthenticateAsync(SoftmakeAll.SDK.Fluent.Authentication.ICredentials Credentials)
        {
            if (Credentials != null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = Credentials;

                // From AccessKey
                if (Credentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Basic {System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{Credentials.ClientID}@{Credentials.ContextIdentifier.ToString().ToLower()}:{Credentials.ClientSecret}"))}";
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Store();
                    await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                    return;
                }
            }
            else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                try
                {
                    System.Text.Json.JsonElement CacheData = SoftmakeAll.SDK.Fluent.GeneralCacheHelper.ReadString().ToJsonElement();
                    if (!(CacheData.IsValid()))
                    {
                        throw new System.Exception();
                    }

                    // From AccessKey
                    if (CacheData.GetInt32("AuthType") == (int)SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetGuid("ContextIdentifier"), CacheData.GetString("ClientID"), null, (SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes)CacheData.GetInt32("AuthType"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = CacheData.GetString("Authorization");
                        if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization))
                        {
                            throw new System.Exception();
                        }

                        await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                        return;
                    }
                    else
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetJsonElement("AppMetadata").EnumerateObject().First().Value.GetGuid("client_id"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType = SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive;
                    }
                }
                catch { }
            }

            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                throw new System.Exception("Invalid Credentials from cache.");
            }


            // From AccessKey
            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
            {
                return;
            }


            // From Public Client Application
            if ((SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null) || (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.ExpiresOn.Subtract(System.DateTimeOffset.UtcNow).TotalMinutes <= 5.0D))
            {
                System.String[] Scopes = new System.String[] { "openid", "https://softmakeb2c.onmicrosoft.com/48512da7-b030-4e62-be61-9e19b2c52d8a/user_impersonation" };
                if (SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication == null)
                {
                    if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "A_signup_signin", "http://localhost:1435");
                    }
                    else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "_ROPC");
                    }
                    else
                    {
                        throw new System.Exception("Invalid authentication type.");
                    }
                }

                // Getting existing Account in cache
                try
                {
                    System.Collections.Generic.IEnumerable <Microsoft.Identity.Client.IAccount> Accounts = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.GetAccountsAsync();

                    if (Accounts.Any())
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenSilent(Scopes, Accounts.FirstOrDefault()).ExecuteAsync();

                        if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult != null)
                        {
                            SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                            await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                            return;
                        }
                    }
                }
                catch
                {
                    SoftmakeAll.SDK.Fluent.GeneralCacheHelper.Clear();
                }


                if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                {
                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenInteractive(Scopes).WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin).ExecuteAsync();
                    }
                    catch { }
                }
                else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                {
                    if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret))
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Authentication aborted. Please, re-enter credentials.");
                    }

                    System.Security.SecureString Password = new System.Security.SecureString();
                    foreach (System.Char Char in SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret)
                    {
                        Password.AppendChar(Char);
                    }
                    Password.MakeReadOnly();

                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenByUsernamePassword(Scopes, SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientID, Password).ExecuteAsync();

                        Password.Dispose();
                    }
                    catch
                    {
                        Password.Dispose();
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Invalid username or password.");
                    }
                }

                if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                    throw new System.Exception("Authentication aborted.");
                }


                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                return;
            }
        }
Esempio n. 11
0
            public void Configure(string name, OpenIdConnectOptions options)
            {
                options.ClientId             = azureOptions.ClientId;
                options.Authority            = $"{azureOptions.Instance}{azureOptions.TenantId}/v2.0";
                options.UseTokenLifetime     = true;
                options.CallbackPath         = azureOptions.CallbackPath;
                options.RequireHttpsMetadata = env.IsProduction();
                options.TokenValidationParameters.NameClaimType = "preferred_username";
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Prompt       = "select_account";

                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.Scope.Add("offline_access");
                // sometimes need admin approval: options.Scope.Add("user.read");

                if (azureOptions.DefaultScopes != null && azureOptions.DefaultScopes.Length > 0)
                {
                    foreach (var scope in azureOptions.DefaultScopes)
                    {
                        options.Scope.Add(scope);
                    }
                }

                if (azureOptions.ValidIssuers != null && azureOptions.ValidIssuers.Length > 0)
                {
                    options.TokenValidationParameters.ValidIssuers = azureOptions.ValidIssuers;
                }

                options.Events = new OpenIdConnectEvents
                {
                    OnUserInformationReceived = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnTicketReceived = context =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        logger.LogError("OnAuthenticationFailed", context.Exception);
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProviderForSignOut = context =>
                    {
                        System.Security.Claims.ClaimsPrincipal user = context.HttpContext.User;

                        context.ProtocolMessage.LoginHint  = user.GetLoginHint();
                        context.ProtocolMessage.DomainHint = user.GetDomainHint();

                        tokenService.RemoveAccount(user);
                        return(Task.FromResult(true));
                    },
                    OnRedirectToIdentityProvider = context =>
                    {
                        System.Collections.Generic.IDictionary <string, object> properties =
                            context.Properties.Parameters;
                        if (properties.ContainsKey("scopes"))
                        {
                            var scopes = properties["scopes"] as string[];
                            if (scopes.Length > 0)
                            {
                                var encoded = string.Join(" ", scopes);
                                context.ProtocolMessage.Scope = context.ProtocolMessage.Scope + " " + encoded;
                            }
                        }

                        return(Task.CompletedTask);
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        // As AcquireTokenByAuthorizationCode is asynchronous we want to tell ASP.NET core
                        // that we are handing the code even if it's not done yet, so that it does
                        // not concurrently call the Token endpoint.
                        context.HandleCodeRedemption();

                        var code = context.ProtocolMessage.Code;

                        Microsoft.Identity.Client.AuthenticationResult result =
                            await tokenService.GetAccessTokenByAuthorizationCodeAsync(context.Principal, code);

                        // Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it
                        // and will not send the OAuth 2.0 request in case a further call to
                        // AcquireTokenByAuthorizationCode in the future for incremental consent
                        // (getting a code requesting more scopes)
                        // Share the ID Token so that the identity of the user is known in the application (in
                        // HttpContext.User)
                        context.HandleCodeRedemption(null, result.IdToken);
                    }
                };
            }
            public void Configure(string name, OpenIdConnectOptions options)
            {
                // Set the application id
                options.ClientId = _azureOptions.ClientId;

                // the authority {Instance}/{Tenant}/v2.0
                // ASP.NET uses v1.0 by default
                options.Authority        = $"{_azureOptions.Instance}{_azureOptions.TenantId}/v2.0";
                options.UseTokenLifetime = true;
                // the redirect Uri: constructed from host:port/signin-oidc
                options.CallbackPath = _azureOptions.CallbackPath;
                // we are in development environment, don't do this in production
                options.RequireHttpsMetadata = false;
                // set name of user name claim
                options.TokenValidationParameters.NameClaimType = "preferred_username";
                // We ask ASP.NET to request a Code and an Id Token
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                //options.Scope.Add("https://graph.microsoft.com/User.Read");
                //options.Scope.Add("https://graph.microsoft.com/Mail.ReadWrite");
                //options.Scope.Add("https://graph.microsoft.com/Tasks.ReadWrite.Shared");
                options.Scope.Add("offline_access");

                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = context =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProviderForSignOut = context =>
                    {
                        System.Security.Claims.ClaimsPrincipal user = context.HttpContext.User;

                        context.ProtocolMessage.LoginHint  = user.GetLoginHint();
                        context.ProtocolMessage.DomainHint = user.GetDomainHint();

                        _tokenService.RemoveAccount(user);
                        return(Task.FromResult(true));
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        // As AcquireTokenByAuthorizationCode is asynchronous we want to tell ASP.NET core
                        // that we are handing the code even if it's not done yet, so that it does
                        // not concurrently call the Token endpoint.
                        context.HandleCodeRedemption();

                        string code = context.ProtocolMessage.Code;

                        Microsoft.Identity.Client.AuthenticationResult result = await _tokenService.GetAccessTokenByAuthorizationCodeAsync(context.Principal, code);

                        // Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it
                        // and will not send the OAuth 2.0 request in case a further call to
                        // AcquireTokenByAuthorizationCode in the future for incremental consent
                        // (getting a code requesting more scopes)
                        // Share the ID Token so that the identity of the user is known in the application (in
                        // HttpContext.User)
                        context.HandleCodeRedemption(null, result.IdToken);
                    }
                };
            }
Esempio n. 13
0
        //async void GetMovies(object sender, EventArgs args)
        //{
        //    //var dataService = new CosmosService();

        //    //var reviews = await dataService.GetReviewsForMovie("b404bb8f-f9c9-4389-9fa6-26aca20104fe");

        //    //var sb = new StringBuilder();
        //    //foreach (var item in reviews)
        //    //{
        //    //    sb.AppendLine(item.reviewText);
        //    //}

        //    //theMovies.Text = sb.ToString();
        //}

        async void Login(object sender, EventArgs args)
        {
            authResult = await authService.Login();
        }