Example #1
0
 protected void ConfigJWTToken(IServiceCollection services, IConfiguration Configuration)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
         options.RequireHttpsMetadata      = false;
         options.SaveToken                 = true;
         options.TokenValidationParameters =
             new TokenValidationParameters
         {
             ClockSkew                = TimeSpan.Zero,//.FromMinutes(MixService.GetAuthConfig<int>("ClockSkew")), //x minute tolerance for the expiration date
             ValidateIssuer           = MixService.GetAuthConfig <bool>("ValidateIssuer"),
             ValidateAudience         = MixService.GetAuthConfig <bool>("ValidateAudience"),
             ValidateLifetime         = MixService.GetAuthConfig <bool>("ValidateLifetime"),
             ValidateIssuerSigningKey = MixService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
             ValidIssuer              = MixService.GetAuthConfig <string>("Issuer"),
             ValidAudience            = MixService.GetAuthConfig <string>("Audience"),
             IssuerSigningKey         = JwtSecurityKey.Create(MixService.GetAuthConfig <string>("SecretKey"))
         };
         options.Events = new JwtBearerEvents
         {
             OnAuthenticationFailed = context =>
             {
                 Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                 return(Task.CompletedTask);
             },
             OnTokenValidated = context =>
             {
                 Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                 return(Task.CompletedTask);
             },
         };
     });
 }
 protected void ConfigCookieAuth(IServiceCollection services, IConfiguration Configuration)
 {
     services.ConfigureApplicationCookie(options =>
     {
         options.Cookie.HttpOnly   = true;
         options.Cookie.MaxAge     = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
         options.Cookie.Expiration = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
         options.LoginPath         = "/security/login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
         options.LogoutPath        = "/";               // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
         options.AccessDeniedPath  = "/security/login"; // If the MixConstants.Default.DefaultCulture is not set here, ASP.NET Core will default to /Account/AccessDenied
         options.SlidingExpiration = true;
     });
 }
        private async Task <AccessTokenViewModel> GenerateAccessTokenAsync(ApplicationUser user, bool isRemember)
        {
            var    dtIssued              = DateTime.UtcNow;
            var    dtExpired             = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
            var    dtRefreshTokenExpired = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("RefreshTokenExpiration"));
            string refreshTokenId        = string.Empty;
            string refreshToken          = string.Empty;

            if (isRemember)
            {
                refreshToken = Guid.NewGuid().ToString();
                RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel(
                    new RefreshTokens()
                {
                    Id        = refreshToken,
                    Email     = user.Email,
                    IssuedUtc = dtIssued,
                    ClientId  = MixService.GetAuthConfig <string>("Audience"),
                    Username  = user.UserName,
                    //Subject = SWCmsConstants.AuthConfiguration.Audience,
                    ExpiresUtc = dtRefreshTokenExpired
                });

                var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync();

                refreshTokenId = saveRefreshTokenResult.Data?.Id;
            }

            AccessTokenViewModel token = new AccessTokenViewModel()
            {
                Access_token  = await GenerateTokenAsync(user, dtExpired, refreshToken),
                Refresh_token = refreshTokenId,
                Token_type    = MixService.GetAuthConfig <string>("TokenType"),
                Expires_in    = MixService.GetAuthConfig <int>("CookieExpiration"),
                //UserData = user,
                Issued  = dtIssued,
                Expires = dtExpired,
                LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration")
            };

            return(token);
        }
        private async Task <string> GenerateTokenAsync(ApplicationUser user, DateTime expires, string refreshToken)
        {
            List <Claim> claims = await GetClaimsAsync(user);

            claims.AddRange(new[]
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("Username", user.UserName),
                new Claim("RefreshToken", refreshToken)
            });
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: MixService.GetAuthConfig <string>("Issuer"),
                audience: MixService.GetAuthConfig <string>("Audience"),
                notBefore: DateTime.UtcNow,
                claims: claims,
                // our token will live 1 hour, but you can change you token lifetime here
                expires: expires,
                signingCredentials: new SigningCredentials(JwtSecurityKey.Create(MixService.GetAuthConfig <string>("SecretKey")), SecurityAlgorithms.HmacSha256));

            return(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken));
        }
        protected void ConfigCookieAuth(IServiceCollection services, IConfiguration Configuration)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(
                options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.Cookie.MaxAge     = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
                options.Cookie.Expiration = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
                options.LoginPath         = "/" + MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultCulture) + "/Portal/Auth/Login";  // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath        = "/" + MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultCulture) + "/Portal/Auth/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath  = "/";                                                                                                           // If the MixConstants.Default.DefaultCulture is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;

                options.Events = new CookieAuthenticationEvents()
                {
                    OnValidatePrincipal = CookieValidator.ValidateAsync
                };
            }
                );
        }
        private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = MixService.GetAuthConfig <bool>("ValidateIssuer"),
                ValidateAudience         = MixService.GetAuthConfig <bool>("ValidateAudience"),
                ValidateLifetime         = MixService.GetAuthConfig <bool>("ValidateLifetime"),
                ValidateIssuerSigningKey = MixService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
                IssuerSigningKey         = JwtSecurityKey.Create(MixService.GetAuthConfig <string>("SecretKey"))
            };

            var           tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken securityToken;
            var           principal        = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
            var           jwtSecurityToken = securityToken as JwtSecurityToken;

            if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new SecurityTokenException("Invalid token");
            }

            return(principal);
        }
Example #7
0
        public static IServiceCollection AddMixAuthorize(this IServiceCollection services, IConfiguration Configuration)
        {
            PasswordOptions pOpt = new PasswordOptions()
            {
                RequireDigit           = false,
                RequiredLength         = 6,
                RequireLowercase       = false,
                RequireNonAlphanumeric = false,
                RequireUppercase       = false
            };

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password = pOpt;
            })
            .AddEntityFrameworkStores <MixDbContext>()
            .AddDefaultTokenProviders()
            .AddUserManager <UserManager <ApplicationUser> >()

            ;

            services.AddAuthorization();

            services.AddAuthentication("Bearer")
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ClockSkew                = TimeSpan.Zero,//.FromMinutes(MixService.GetAuthConfig<int>("ClockSkew")), //x minute tolerance for the expiration date
                    ValidateIssuer           = MixService.GetAuthConfig <bool>("ValidateIssuer"),
                    ValidateAudience         = MixService.GetAuthConfig <bool>("ValidateAudience"),
                    ValidateLifetime         = MixService.GetAuthConfig <bool>("ValidateLifetime"),
                    ValidateIssuerSigningKey = MixService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
                    //ValidIssuer = MixService.GetAuthConfig<string>("Issuer"),
                    //ValidAudience = MixService.GetAuthConfig<string>("Audience"),
                    ValidIssuers     = MixService.GetAuthConfig <string>("Issuers").Split(','),
                    ValidAudiences   = MixService.GetAuthConfig <string>("Audiences").Split(','),
                    IssuerSigningKey = JwtSecurityKey.Create(MixService.GetAuthConfig <string>("SecretKey"))
                };
                // TODO Handle Custom Auth
                //options.Events = new JwtBearerEvents
                //{
                //    OnAuthenticationFailed = context =>
                //    {
                //        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                //        return Task.CompletedTask;
                //    },
                //    OnTokenValidated = context =>
                //    {
                //        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                //        return Task.CompletedTask;
                //    },

                //};
            });
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.MaxAge   = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
                options.ExpireTimeSpan  = TimeSpan.FromMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
                //options.Cookie.Expiration = TimeSpan.FromMinutes(MixService.GetAuthConfig<int>("CookieExpiration"));
                options.LoginPath         = "/security/login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath        = "/";               // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath  = "/security/login"; // If the MixConstants.Default.DefaultCulture is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;
            });
            return(services);
        }