Ejemplo n.º 1
0
 protected void ConfigJWTToken(IServiceCollection services, IConfiguration Configuration)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
         options.TokenValidationParameters =
             new TokenValidationParameters
         {
             ClockSkew                = TimeSpan.FromMinutes(SioService.GetAuthConfig <int>("ClockSkew")),
             ValidateIssuer           = false,
             ValidateAudience         = false,
             ValidateLifetime         = true,
             ValidateIssuerSigningKey = true,
             ValidIssuer              = SioService.GetAuthConfig <string>("Issuer"),
             ValidAudience            = SioService.GetAuthConfig <string>("Audience"),
             IssuerSigningKey         = JwtSecurityKey.Create(SioService.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);
             }
         };
     });
 }
Ejemplo n.º 2
0
        private async Task <AccessTokenViewModel> GenerateAccessTokenAsync(ApplicationUser user, bool isRemember)
        {
            var    dtIssued              = DateTime.UtcNow;
            var    dtExpired             = dtIssued.AddMinutes(SioService.GetAuthConfig <int>("CookieExpiration"));
            var    dtRefreshTokenExpired = dtIssued.AddMinutes(SioService.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  = SioService.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    = SioService.GetAuthConfig <string>("TokenType"),
                Expires_in    = SioService.GetAuthConfig <int>("CookieExpiration"),
                //UserData = user,
                Issued  = dtIssued,
                Expires = dtExpired,
                LastUpdateConfiguration = SioService.GetConfig <DateTime?>("LastUpdateConfiguration")
            };

            return(token);
        }
Ejemplo n.º 3
0
        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: SioService.GetAuthConfig <string>("Issuer"),
                audience: SioService.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(SioService.GetAuthConfig <string>("SecretKey")), SecurityAlgorithms.HmacSha256));

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

                options.Events = new CookieAuthenticationEvents()
                {
                    OnValidatePrincipal = CookieValidator.ValidateAsync
                };
            }
                );
        }
Ejemplo n.º 5
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(SioService.GetAuthConfig<int>("ClockSkew")), //x minute tolerance for the expiration date
             ValidateIssuer           = SioService.GetAuthConfig <bool>("ValidateIssuer"),
             ValidateAudience         = SioService.GetAuthConfig <bool>("ValidateAudience"),
             ValidateLifetime         = SioService.GetAuthConfig <bool>("ValidateLifetime"),
             ValidateIssuerSigningKey = SioService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
             //ValidIssuer = SioService.GetAuthConfig<string>("Issuer"),
             //ValidAudience = SioService.GetAuthConfig<string>("Audience"),
             ValidIssuers     = SioService.GetAuthConfig <string>("Issuers").Split(','),
             ValidAudiences   = SioService.GetAuthConfig <string>("Audiences").Split(','),
             IssuerSigningKey = JwtSecurityKey.Create(SioService.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);
             },
         };
     });
     services.AddAuthentication("Bearer");
     //services.Configure<IpSecuritySettings>(Configuration.GetSection("IpSecuritySettings"));
 }
Ejemplo n.º 6
0
        private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = SioService.GetAuthConfig <bool>("ValidateIssuer"),
                ValidateAudience         = SioService.GetAuthConfig <bool>("ValidateAudience"),
                ValidateLifetime         = SioService.GetAuthConfig <bool>("ValidateLifetime"),
                ValidateIssuerSigningKey = SioService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
                IssuerSigningKey         = JwtSecurityKey.Create(SioService.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);
        }