Beispiel #1
0
        public void EncodingUtilitiesTest()
        {
            var data = EncodingUtilities.StringToByteArray("test", "utf-8");

            Assert.AreEqual("test", EncodingUtilities.ByteArrayToString(data, "utf-8"));

            data = EncodingUtilities.StringToByteArray("test", "ascii");
            Assert.AreEqual("test", EncodingUtilities.ByteArrayToString(data, "ascii"));

            data = EncodingUtilities.StringToByteArray("test", "utf-16");
            Assert.AreEqual("test", EncodingUtilities.ByteArrayToString(data, "utf-16"));

            Assert.ThrowsException <Exception>(() => { EncodingUtilities.StringToByteArray("test", null); });
            Assert.ThrowsException <Exception>(() => { EncodingUtilities.StringToByteArray("test", "utf16"); });
            Assert.ThrowsException <Exception>(() => { EncodingUtilities.StringToByteArray("test", "u"); });
        }
        public IActionResult Token(AuthRequest authRequest)
        {
            using (var session = _manager.OpenSession())
            {
                var success = IdentityHelper.SignIn(authRequest.Username, authRequest.Password, false);

                ActionResult response = new EmptyResult();

                if (success == true)
                {
                    var userInfo = IdentityHelper.GetApplicationUserByName(authRequest.Username);

                    var claims = userInfo.Permissions.Select(p => new Claim(Model.ClaimTypes.Permission, p.Name)).ToList();
                    claims.Add(new Claim(ClaimTypes.Name, userInfo.UserName));
                    if (!string.IsNullOrWhiteSpace(userInfo.Email))
                    {
                        claims.Add(new Claim(Model.ClaimTypes.Email, userInfo.Email));
                    }
                    var userRoles = userInfo.Roles.Select(r => new Claim(ClaimTypes.Role, r.Name));
                    claims.AddRange(userRoles);

                    var key = EncodingUtilities.StringToByteArray(_jwtKey, "ascii");
                    var signingCredential = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
                    var tokenDescriptor   = new JwtSecurityToken(null, null, claims, expires: _jwtExpirationTime, signingCredentials: signingCredential);
                    var token             = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);

                    var result = new
                    {
                        idToken   = token,
                        expiresIn = tokenDescriptor.ValidTo,
                    };
                    response = Ok(result);
                }

                _manager.CloseSession();
                return(response);
            }
        }
        public static void AddIdentityManager(this IServiceCollection services, IConfiguration configuration, PasswordPolicyConfig passwordPolicy = null, ExternalLoginConfig externalLoginConfig = null)
        {
            if (passwordPolicy == null)
            {
                passwordPolicy = new PasswordPolicyConfig();
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddCustomIdentity <Model.IdentityUser, IdentityRole>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = passwordPolicy.RequireDigit;
                options.Password.RequireLowercase       = passwordPolicy.RequireLowercase;
                options.Password.RequireNonAlphanumeric = passwordPolicy.RequireNonLetterOrDigit;
                options.Password.RequireUppercase       = passwordPolicy.RequireUppercase;
                options.Password.RequiredLength         = passwordPolicy.RequiredLength;
                options.Password.RequiredUniqueChars    = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = false;

                // User settings.
                options.User.RequireUniqueEmail        = false;
                options.User.AllowedUserNameCharacters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+";
            })
            .AddRoles <IdentityRole>()
            .AddRoleStore <RoleStore <IdentityRole> >()
            .AddUserStore <UserStore>()
            .AddUserManager <CustomUserManager>()
            .AddDefaultTokenProviders();

            var key = EncodingUtilities.StringToByteArray(configuration.GetValue("configuration:appSettings:add:JWTKey:value", "MIksRlTn0KG6nmjW*fzq*FYTY0RifkNQE%QTqdfS81CgNEGtUmMCY5XEgPTSL&28"), "ascii");

            var authenticationBuilder = services
                                        .AddAuthentication(options =>
            {
                options.DefaultScheme = IdentityConstants.ApplicationScheme;
            });

            authenticationBuilder.AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            if (externalLoginConfig != null && externalLoginConfig.IsGoogleEnabled)
            {
                authenticationBuilder.AddGoogle(options =>
                {
                    options.ClientId     = externalLoginConfig.GoogleClientId;
                    options.ClientSecret = externalLoginConfig.GoogleClientSecret;
                });
            }

            if (externalLoginConfig != null && externalLoginConfig.IsFacebookEnabled)
            {
                authenticationBuilder.AddFacebook(options =>
                {
                    options.AppId     = externalLoginConfig.FacebookClientId;
                    options.AppSecret = externalLoginConfig.FacebookClientSecret;
                });
            }

            services.AddTransient <CustomUserManager>();
            services.AddTransient <SignInManager <Model.IdentityUser> >();

            services.AddSingleton <OperationAuthorizationService>();
            services.AddSingleton <IAuthorizationPolicyProvider, OperationPolicyProvider>();
            services.AddSingleton <IAuthorizationHandler, OperationAuthorizationHandler>();

            //services.AddAuthentication(IISDefaults.AuthenticationScheme);
        }