Exemplo n.º 1
0
 public AuthenticateController(
     IAuthenticateActions authenticateActions,
     IDataProtectionProvider dataProtectionProvider,
     IEncoder encoder,
     ITranslationManager translationManager,
     ISimpleIdentityServerEventSource simpleIdentityServerEventSource,
     IUrlHelperFactory urlHelperFactory,
     IActionContextAccessor actionContextAccessor,
     IEventPublisher eventPublisher,
     IAuthenticationService authenticationService,
     IAuthenticationSchemeProvider authenticationSchemeProvider,
     IUserActions userActions,
     IPayloadSerializer payloadSerializer,
     AuthenticateOptions authenticateOptions,
     IConfigurationService configurationService,
     IAuthenticateHelper authenticateHelper) : base(authenticationService, authenticateOptions)
 {
     _authenticateActions             = authenticateActions;
     _dataProtector                   = dataProtectionProvider.CreateProtector("Request");
     _encoder                         = encoder;
     _translationManager              = translationManager;
     _simpleIdentityServerEventSource = simpleIdentityServerEventSource;
     _urlHelper                       = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
     _eventPublisher                  = eventPublisher;
     _payloadSerializer               = payloadSerializer;
     _authenticationSchemeProvider    = authenticationSchemeProvider;
     _configurationService            = configurationService;
     _authenticateHelper              = authenticateHelper;
 }
Exemplo n.º 2
0
        public async Task <IAuthenticationResponse> AuthenticateAsync(AuthenticateOptions authenticateOptions, CancellationToken cancellationToken = default(CancellationToken))
        {
            var authenticationRequest = new AuthenticationRequest()
            {
                Username   = authenticateOptions.Username,
                Password   = authenticateOptions.Password,
                Audience   = authenticateOptions.Audience,
                RelayState = authenticateOptions.RelayState,
                StateToken = authenticateOptions.StateToken,
                Options    = new AuthenticationRequestOptions()
                {
                    MultiOptionalFactorEnroll = authenticateOptions.MultiOptionalFactorEnroll,
                    WarnBeforePasswordExpired = authenticateOptions.WarnBeforePasswordExpired,
                },

                Context = new AuthenticationRequestContext()
                {
                    DeviceToken = authenticateOptions.DeviceToken,
                },
            };

            var request = new HttpRequest
            {
                Uri     = "/api/v1/authn",
                Payload = authenticationRequest,
            };

            request.Headers["X-Forwarded-For"] = this.GetXForwadedIP();

            return(await this.PostAsync <AuthenticationResponse>(
                       request, cancellationToken).ConfigureAwait(false));
        }
        public async Task EnrollSmsFactor()
        {
            var oktaClient = new OktaClient();
            var guid       = Guid.NewGuid();
            // MFA Group w/ SMS policy
            var groupId     = "{groupId}";
            var createdUser = await oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = "John",
                    LastName  = "Enroll-SMS",
                    Email     = $"john-enroll-sms-dotnet-authn-{guid}@example.com",
                    Login     = $"john-enroll-sms-dotnet-authn-{guid}@example.com",
                },
                Password = "******",
                Activate = true,
            });

            try
            {
                await oktaClient.Groups.AddUserToGroupAsync(groupId, createdUser.Id);

                var authnClient = TestAuthenticationClient.Create();

                var authnOptions = new AuthenticateOptions()
                {
                    Username = $"john-enroll-sms-dotnet-authn-{guid}@example.com",
                    Password = "******",
                    MultiOptionalFactorEnroll = true,
                    WarnBeforePasswordExpired = true,
                };

                var authnResponse = await authnClient.AuthenticateAsync(authnOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().NotBeNull();
                authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().HaveCountGreaterThan(0);
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.MfaEnroll);

                var enrollOptions = new EnrollSmsFactorOptions()
                {
                    PhoneNumber = "+1 415 555 5555",
                    StateToken  = authnResponse.StateToken,
                };

                authnResponse = await authnClient.EnrollFactorAsync(enrollOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.MfaEnrollActivate);
                authnResponse.GetProperty <Factor>("factor").Should().NotBeNull();
                authnResponse.GetProperty <Factor>("factor").Profile.GetProperty <string>("phoneNumber").Should().NotBeNullOrEmpty();
            }
            finally
            {
                await createdUser.DeactivateAsync();

                await createdUser.DeactivateOrDeleteAsync();
            }
        }
 public SessionController(IAuthenticationService authenticationService,
                          AuthenticateOptions authenticateOptions, IClientRepository clientRepository,
                          IJwtParser jwtParser)
 {
     _authenticationService = authenticationService;
     _authenticateOptions   = authenticateOptions;
     _clientRepository      = clientRepository;
     _jwtParser             = jwtParser;
 }
Exemplo n.º 5
0
 private void Button1_Click(object sender, EventArgs e)
 {
     // Primary Authentication
     var authnOptions = new AuthenticateOptions()
     {
         Username = userName,
         Password = password,
         // DeviceToken = deviceToken,
         WarnBeforePasswordExpired = true,
     };
     var authenticationResponse = this.client.AuthenticateAsync(authnOptions);
     // this.stateController.ProcessAuthnResponse(authenticationResponse);
 }
 public AuthorizationController(
     IAuthorizationActions authorizationActions,
     IDataProtectionProvider dataProtectionProvider,
     IEncoder encoder,
     IActionResultParser actionResultParser,
     IJwtParser jwtParser,
     AuthenticateOptions authenticateOptions)
 {
     _authorizationActions = authorizationActions;
     _dataProtector        = dataProtectionProvider.CreateProtector("Request");
     _encoder             = encoder;
     _actionResultParser  = actionResultParser;
     _jwtParser           = jwtParser;
     _authenticateOptions = authenticateOptions;
 }
Exemplo n.º 7
0
        public async Task <ActionResult> LoginAsync(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Login"));
            }

            var authnOptions = new AuthenticateOptions()
            {
                Username = model.UserName,
                Password = model.Password,
            };

            try
            {
                var authnResponse = await _oktaAuthenticationClient.AuthenticateAsync(authnOptions).ConfigureAwait(false);

                if (authnResponse.AuthenticationStatus == AuthenticationStatus.Success)
                {
                    var identity = new ClaimsIdentity(
                        new[] { new Claim(ClaimTypes.Name, model.UserName) },
                        DefaultAuthenticationTypes.ApplicationCookie);

                    _authenticationManager.SignIn(new AuthenticationProperties {
                        IsPersistent = model.RememberMe
                    }, identity);

                    return(RedirectToAction("Index", "Home"));
                }
                else if (authnResponse.AuthenticationStatus == AuthenticationStatus.PasswordExpired)
                {
                    Session["stateToken"] = authnResponse.StateToken;

                    return(RedirectToAction("ChangePassword", "Manage"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, $"Invalid login attempt: {authnResponse.AuthenticationStatus}");
                    return(View("Login", model));
                }
            }
            catch (OktaApiException exception)
            {
                ModelState.AddModelError(string.Empty, $"Invalid login attempt: {exception.ErrorSummary}");
                return(View("Login", model));
            }
        }
        public async Task AuthenticateUserWithExpiredPassword()
        {
            var oktaClient = new OktaClient();
            var guid       = Guid.NewGuid();

            var createdUser = await oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = "John",
                    LastName  = "Test",
                    Email     = $"john-expired-pass-dotnet-authn-{guid}@example.com",
                    Login     = $"john-expired-pass-dotnet-authn-{guid}@example.com",
                },
                Password = "******",
                Activate = true,
            });

            try
            {
                await createdUser.ExpirePasswordAsync();

                var authClient = TestAuthenticationClient.Create();

                var authnOptions = new AuthenticateOptions()
                {
                    Username = $"john-expired-pass-dotnet-authn-{guid}@example.com",
                    Password = "******",
                    MultiOptionalFactorEnroll = true,
                    WarnBeforePasswordExpired = true,
                };

                var authnResponse = await authClient.AuthenticateAsync(authnOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.StateToken.Should().NotBeNullOrEmpty();
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.PasswordExpired);
                authnResponse.Links.Should().NotBeNull();
            }
            finally
            {
                await createdUser.DeactivateAsync();

                await createdUser.DeactivateOrDeleteAsync();
            }
        }
 public ConsentController(
     IConsentActions consentActions,
     IDataProtectionProvider dataProtectionProvider,
     ITranslationManager translationManager,
     IEventPublisher eventPublisher,
     IEventAggregateRepository eventAggregateRepository,
     IAuthenticationService authenticationService,
     IUserActions usersAction,
     IPayloadSerializer payloadSerializer,
     AuthenticateOptions authenticateOptions) : base(authenticationService, authenticateOptions)
 {
     _consentActions           = consentActions;
     _dataProtector            = dataProtectionProvider.CreateProtector("Request");
     _translationManager       = translationManager;
     _eventPublisher           = eventPublisher;
     _eventAggregateRepository = eventAggregateRepository;
     _payloadSerializer        = payloadSerializer;
 }
        public async Task AuthenticateUserWithPendingEnroll()
        {
            var client = TestAuthenticationClient.Create();

            var authnOptions = new AuthenticateOptions()
            {
                Username = "******",
                Password = "******",
                MultiOptionalFactorEnroll = true,
                WarnBeforePasswordExpired = true,
            };

            var authnResponse = await client.AuthenticateAsync(authnOptions);

            authnResponse.Should().NotBeNull();
            authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().NotBeNull();
            authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().HaveCountGreaterThan(0);
            authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.MfaEnroll);
        }
        public async Task AuthenticateUserWithInvalidCredentials()
        {
            var oktaClient = new OktaClient();
            var guid       = Guid.NewGuid();

            var createdUser = await oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = "John",
                    LastName  = "Test",
                    Email     = $"john-invalid-cred-dotnet-authn-{guid}@example.com",
                    Login     = $"john-invalid-cred-dotnet-authn-{guid}@example.com",
                },
                Password = "******",
                Activate = true,
            });

            var authClient = TestAuthenticationClient.Create();

            var authnOptions = new AuthenticateOptions()
            {
                Username = $"john-invalid-cred-dotnet-authn-{guid}@example.com",
                Password = "******",
                MultiOptionalFactorEnroll = true,
                WarnBeforePasswordExpired = true,
            };

            try
            {
                Func <Task> act = async() => await authClient.AuthenticateAsync(authnOptions);

                act.Should().Throw <OktaApiException>();
            }
            finally
            {
                await createdUser.DeactivateAsync();

                await createdUser.DeactivateOrDeleteAsync();
            }
        }
Exemplo n.º 12
0
    public async void Login()
    {
        var client = new AuthenticationClient(new OktaClientConfiguration
        {
            OktaDomain = OktaDomain,
        });

        var authnOptions = new AuthenticateOptions()
        {
            //Thank you to arvind-balamurugan: https://github.com/arvind-balamurugan for discovering and providing this resolution the invalid format error on Mac, iOS, Android.
            //Explicitly passing UserAgent with the client OS description. Passing UserAgent explicitly is required for Mac/iOS/Android but not for Windows.
            UserAgent = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
            Username  = Username.text.ToString(),
            Password  = Password.text.ToString(),
        };

        try
        {
            var authnResponse = await client.AuthenticateAsync(authnOptions);

            Debug.Log("Authentication Status: " + authnResponse.AuthenticationStatus);
            if (authnResponse.AuthenticationStatus == "SUCCESS")
            {
                //Store the token
                Debug.Log(authnResponse.SessionToken);
                isAuthenticated = true;

                OpenPanel(initiallyOpen);
            }
            else
            {
                //Handle Errors
                Debug.Log("Authentication Failed...");
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
Exemplo n.º 13
0
        public static async Task <bool> Login(string email, string password)
        {
            var config = new OktaClientConfiguration {
                OktaDomain = "https://dev-846291.oktapreview.com",
            };
            var authClient = new AuthenticationClient(config);

            var authnOptions = new AuthenticateOptions {
                Username = email, Password = password
            };

            try
            {
                var authnResponse = await authClient.AuthenticateAsync(authnOptions);

                return(authnResponse.AuthenticationStatus == AuthenticationStatus.Success);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 14
0
        public async Task <string> GetTokenAsync(string email)
        {
            var identity = await GetIdentity(email);

            if (identity == null)
            {
                return(string.Empty);
            }

            var timeNow = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: AuthenticateOptions.ISSUER,
                audience: AuthenticateOptions.AUDIENCE,
                notBefore: timeNow,
                claims: identity.Claims,
                expires: timeNow.Add(TimeSpan.FromMinutes(AuthenticateOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthenticateOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)
                );

            return(new JwtSecurityTokenHandler().WriteToken(jwt));
        }
Exemplo n.º 15
0
        public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity <IdentityUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedAccount  = true;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.SignIn.RequireConfirmedAccount  = false;
            })
            .AddEntityFrameworkStoresCustom()
            .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthenticateOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = AuthenticateOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthenticateOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <ICartService, CartService>();
            services.AddScoped <IShopService, ShopService>();
            services.AddScoped <ICartHistoryService, CartHistoryService>();

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new ProductProfile());
                mc.AddProfile(new UserProfile());
                mc.AddProfile(new ShopProfile());
                mc.AddProfile(new CartProfile());
                mc.AddProfile(new CartHistoryProfile());
            });
            var mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddTransient <IEmailSender, EmailSender>(i =>
                                                              new EmailSender(
                                                                  configuration["EmailSender:Host"],
                                                                  configuration.GetValue <int>("EmailSender:Port"),
                                                                  configuration.GetValue <bool>("EmailSender:EnableSSL"),
                                                                  configuration.GetValue <string>("TestShopAppUserName"),
                                                                  configuration.GetValue <string>("TestShopAppPassword")
                                                                  )
                                                              );

            services.AddSingleton <IConfiguration>(provider => configuration);
        }
 public UserController(
     IAuthenticationService authenticationService,
     IUserActions userActions,
     AuthenticateOptions authenticateOptions) : base(authenticationService, userActions, authenticateOptions)
 {
 }
        public async Task EnrollSecurityQuestionFactor()
        {
            var oktaClient = new OktaClient();
            var guid       = Guid.NewGuid();
            // MFA Group w/ Security Question policy
            var groupId     = "{groupId}";
            var createdUser = await oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = "John",
                    LastName  = "Enroll-Security-Question",
                    Email     = $"john-enroll-question-dotnet-authn-{guid}@example.com",
                    Login     = $"john-enroll-question-dotnet-authn-{guid}@example.com",
                },
                Password = "******",
                Activate = true,
            });

            try
            {
                await oktaClient.Groups.AddUserToGroupAsync(groupId, createdUser.Id);

                var authnClient = TestAuthenticationClient.Create();

                var authnOptions = new AuthenticateOptions()
                {
                    Username = $"john-enroll-question-dotnet-authn-{guid}@example.com",
                    Password = "******",
                    MultiOptionalFactorEnroll = true,
                    WarnBeforePasswordExpired = true,
                };

                var authnResponse = await authnClient.AuthenticateAsync(authnOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().NotBeNull();
                authnResponse.Embedded.GetArrayProperty <Factor>("factors").Should().HaveCountGreaterThan(0);
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.MfaEnroll);

                var enrollOptions = new EnrollSecurityQuestionFactorOptions()
                {
                    Question   = "name_of_first_plush_toy",
                    Answer     = "blah",
                    StateToken = authnResponse.StateToken,
                };

                authnResponse = await authnClient.EnrollFactorAsync(enrollOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.MfaEnroll);

                // Authenticate after enroll
                authnResponse = await authnClient.AuthenticateAsync(authnOptions);

                authnResponse.Should().NotBeNull();
                authnResponse.AuthenticationStatus.Should().Be(AuthenticationStatus.Success);
            }
            finally
            {
                await createdUser.DeactivateAsync();

                await createdUser.DeactivateOrDeleteAsync();
            }
        }
Exemplo n.º 18
0
 public HomeController(IAuthenticationService authenticationService, AuthenticateOptions options, BasicShellOptions basicShellOptions) : base(authenticationService, options)
 {
     _basicShellOptions = basicShellOptions;
 }
 public BaseController(IAuthenticationService authenticationService, AuthenticateOptions authenticateOptions)
 {
     _authenticationService = authenticationService;
     _authenticateOptions   = authenticateOptions;
 }
 public UserController(IUserActions userActions, ITranslationManager translationManager, IAuthenticationService authenticationService, AuthenticateOptions options) : base(authenticationService, options)
 {
     _userActions        = userActions;
     _translationManager = translationManager;
 }
Exemplo n.º 21
0
        public async Task <ActionResult> LoginAsync(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Login"));
            }

            var authnOptions = new AuthenticateOptions()
            {
                Username = model.UserName,
                Password = model.Password,
            };

            try
            {
                var authnResponse = await _oktaAuthenticationClient.AuthenticateAsync(authnOptions).ConfigureAwait(false);

                Session["rememberMe"] = model.RememberMe;
                if (authnResponse.AuthenticationStatus == AuthenticationStatus.Success)
                {
                    var identity = new ClaimsIdentity(
                        new[] { new Claim(ClaimTypes.Name, model.UserName) },
                        DefaultAuthenticationTypes.ApplicationCookie);

                    _authenticationManager.SignIn(new AuthenticationProperties {
                        IsPersistent = model.RememberMe
                    }, identity);

                    return(RedirectToAction("Index", "Home"));
                }
                else if (authnResponse.AuthenticationStatus == AuthenticationStatus.MfaEnroll)
                {
                    Session["stateToken"] = authnResponse.StateToken;
                    var factors = authnResponse.Embedded.GetArrayProperty <Factor>("factors");
                    Session["factors"] = factors?.Where(x => x.Enrollment.ToUpper() == "REQUIRED").ToList();

                    return(RedirectToAction("SelectFactor", "Manage"));
                }
                else if (authnResponse.AuthenticationStatus == AuthenticationStatus.MfaRequired)
                {
                    Session["stateToken"] = authnResponse.StateToken;

                    var allFactors = authnResponse.Embedded.GetArrayProperty <Factor>("factors");

                    var defaultMfaFactor = allFactors.FirstOrDefault(x => x.Type == "sms" || x.Type == "email");

                    if (defaultMfaFactor != null)
                    {
                        Session["isMfaRequiredFlow"] = true;
                        Session["factorId"]          = defaultMfaFactor.Id;
                        return(RedirectToAction("VerifyFactor", "Manage"));
                    }

                    throw new NotImplementedException($"Unhandled Factor during MFA Auth");
                }
                else if (authnResponse.AuthenticationStatus == AuthenticationStatus.PasswordExpired)
                {
                    Session["stateToken"] = authnResponse.StateToken;

                    return(RedirectToAction("ChangePassword", "Manage"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, $"Invalid login attempt: {authnResponse.AuthenticationStatus}");
                    return(View("Login", model));
                }
            }
            catch (OktaApiException exception)
            {
                ModelState.AddModelError(string.Empty, $"Invalid login attempt: {exception.ErrorSummary}");
                return(View("Login", model));
            }
        }