Пример #1
0
 public UserService(IUserRepository repository, SigningConfiguration signingConfiguration, TokenConfiguration tokenConfiguration, IDistributedCache cache)
 {
     _repository           = repository;
     _signingConfiguration = signingConfiguration;
     _tokenConfiguration   = tokenConfiguration;
     _cache = cache;
 }
Пример #2
0
 public LoginService(IUserRepository repository, SigningConfiguration signingConfiguration, TokenConfiguration tokenConfiguration, IConfiguration configuration)
 {
     _repository           = repository;
     _signingConfiguration = signingConfiguration;
     _tokenConfiguration   = tokenConfiguration;
     _configuration        = configuration;
 }
Пример #3
0
        public static string GetToken(Usuario usuario, TokenConfiguration tokenConfigurations, dynamic signingConfigurations)
        {
            ClaimsIdentity identity = new ClaimsIdentity(
                new GenericIdentity(usuario.Email, "Login"),
                new[] {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                new Claim(JwtRegisteredClaimNames.UniqueName, usuario.Email)
            }
                );

            DateTime dataCriacao   = DateTime.Now;
            DateTime dataExpiracao = dataCriacao +
                                     TimeSpan.FromSeconds(tokenConfigurations.Seconds);

            var handler       = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = tokenConfigurations.Issuer,
                Audience           = tokenConfigurations.Audience,
                SigningCredentials = signingConfigurations.SigningCredentials,
                Subject            = identity,
                NotBefore          = dataCriacao,
                Expires            = dataExpiracao
            });
            var token = handler.WriteToken(securityToken);

            return(token);
        }
Пример #4
0
 public TokenService(
     UserManager <ApplicationUser> userManager,
     IOptions <TokenConfiguration> tokenConfiguration)
 {
     _userManager        = userManager;
     _tokenConfiguration = tokenConfiguration.Value;
 }
Пример #5
0
        private void Authentication(IServiceCollection services)
        {
            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(_configuration.GetSection("TokenConfigurations")).Configure(tokenConfigurations);

            services.AddSingleton(tokenConfigurations);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                // Validates the signing of a received token
                paramsValidation.ValidateIssuerSigningKey = true;

                // Checks if a received token is still valid
                paramsValidation.ValidateLifetime = true;

                // Tolerance time for the expiration of a token (used in case
                // of time synchronization problems between different
                // computers involved in the communication process)
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });
        }
Пример #6
0
 public TokenService(SigninConfiguration signingConfiguration,
                     TokenConfiguration tokenConfigurations, IConfiguration configuration)
 {
     _signingConfiguration = signingConfiguration;
     _tokenConfigurations  = tokenConfigurations;
     _configuration        = configuration;
 }
 public AccountController(IMapper mapper, IAccountService accountService,
                          IOptions <TokenConfiguration> tokenConfigurationOptions)
 {
     _mapper             = mapper;
     _accountService     = accountService;
     _tokenConfiguration = tokenConfigurationOptions.Value;
 }
Пример #8
0
 /// <summary>
 ///     初始化
 /// </summary>
 private void Initinal()
 {
     lock (InitLock)
     {
         if (_isInited)
         {
             return;
         }
         Logger.Debug("TokenManagement init...");
         if (_providers != null && _providers.Count != 0)
         {
             return;
         }
         TokenConfiguration config = TokenConfiguration.GetConfig();
         if (config == null || !config.Enabled)
         {
             return;
         }
         config.ValidateDefaultProvider();
         _providers = config.ProvidersInternal;
         _providers.SetReadOnly();
         _provider = _providers[config.DefaultProvider];
         if (_provider.IsMemoryCache)
         {
             Timer tokenTimer = new Timer();
             tokenTimer.Elapsed += TokenTimer_Elapsed;
             // 设置引发时间的时间间隔 此处设置为5分钟
             tokenTimer.Interval = (config.ClearInvalidTokenSeconds > 0
                 ? config.ClearInvalidTokenSeconds
                 : DefaultClearInvalidTokenSeconds) * 1000;
             tokenTimer.Enabled = true;
         }
         _isInited = true;
     }
 }
Пример #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureService.ConfigureDependeciesService(services);
            ConfigurationRepository.ConfigureDependeciesRepository(services);
            ConfigurationContext.ConfigureDependeciesContext(services);

            var signingConfiguration = new SigningConfiguration();

            services.AddSingleton(signingConfiguration);

            var tokenConfiguration = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(Configuration.GetSection("TokenConfiguration")).Configure(tokenConfiguration);

            services.AddSingleton(tokenConfiguration);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Api em .net core ", Description = "Projeto utilizado para fins didáticos", Version = "v1", Contact = new OpenApiContact
                    {
                        Name = "Uigor Silva Fonseca",
                        Url  = new Uri("https://github.com/uigormarshall")
                    }
                });
            });
            services.AddControllers();
        }
Пример #10
0
        public static void InstallJwtAuthorization(IServiceCollection services)
        {
            var tokenConfig = new TokenConfiguration();

            services.AddAuthentication(x =>

            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenConfig.Secret)),
                    ValidIssuer      = tokenConfig.Issuer,
                    ValidAudience    = tokenConfig.Audience,
                    ValidateIssuer   = true,
                    ValidateAudience = false,
                    ClockSkew        = TimeSpan.FromMinutes(tokenConfig.AccessExpiration)
                };
            });
        }
        public static void RegisterTokenService(IServiceCollection services,
                                                SigningConfiguration signingConfiguration,
                                                TokenConfiguration tokenConfiguration)
        {
            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfiguration.Key;
                paramsValidation.ValidAudience    = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer      = tokenConfiguration.Issuer;

                // Valida a assinatura de um token recebido
                paramsValidation.ValidateIssuerSigningKey = true;

                // Verifica se um token recebido ainda é válido
                paramsValidation.ValidateLifetime = true;

                // Tempo de tolerância para a expiração de um token (utilizado
                // caso haja problemas de sincronismo de horário entre diferentes
                // computadores envolvidos no processo de comunicação)
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });
        }
        public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            TokenConfiguration authenticationConfiguration = new TokenConfiguration();

            configuration.Bind(nameof(TokenConfiguration), authenticationConfiguration);

            services.AddSingleton(authenticationConfiguration);

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authenticationConfiguration.Secret)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            return(services);
        }
Пример #13
0
 public AuthAppService(IMapper mapper, IUserService userService, TokenConfiguration tokenConfiguration, SigningConfigurations signingConfiguration, IUnitOfWork uow) : base(uow)
 {
     _tokenConfiguration   = tokenConfiguration;
     _signingConfiguration = signingConfiguration;
     _userService          = userService;
     _mapper = mapper;
 }
Пример #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure <TokenConfiguration>(Configuration.GetSection(TokenConfiguration.ConfigurationSectionName));

            var tokenConfig = new TokenConfiguration();

            Configuration.GetSection(TokenConfiguration.ConfigurationSectionName).Bind(tokenConfig);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = tokenConfig.Issuer,
                    ValidAudience    = tokenConfig.Audience,
                    IssuerSigningKey = tokenConfig.GetSymmetricSecurityKey()
                };
            });

            services.AddMvc();
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200");
                    builder.AllowAnyHeader();
                });
            });

            var signingConfigurations = new SigningConfiguration();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                // Valida a assinatura de um token recebido
                paramsValidation.ValidateIssuerSigningKey = true;

                // Verifica se um token recebido ainda é válido
                paramsValidation.ValidateLifetime = true;

                // Tempo de tolerância para a expiração de um token (utilizado
                // caso haja problemas de sincronismo de horário entre diferentes
                // computadores envolvidos no processo de comunicação)
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            // Ativa o uso do token como forma de autorizar o acesso
            // a recursos deste projeto
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton(Configuration);
            Bootstrapper.Configure(services);
        }
Пример #16
0
 public UsuarioService(IUsuarioRepository repo, SigningConfigurations signConfig,
                       TokenConfiguration tokenConfig)
 {
     _repo        = repo;
     _signConfig  = signConfig;
     _tokenConfig = tokenConfig;
 }
Пример #17
0
        public object Post([FromBody] User usuario,
                           [FromServices] UserDAO userDAO,
                           [FromServices] SigningConfigurations signingConfigurations,
                           [FromServices] TokenConfiguration tokenConfigurations)
        {
            bool credentialisValid = false;

            if (usuario != null && !string.IsNullOrWhiteSpace(usuario.UserID))
            {
                var usuarioBase = userDAO.Find(usuario.UserID);
                credentialisValid = (usuarioBase != null &&
                                     usuario.UserID == usuarioBase.UserID &&
                                     usuario.AccessKey == usuarioBase.AccessKey);
            }

            if (credentialisValid)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(usuario.UserID, "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, usuario.UserID)
                }
                    );


                DateTime dataCriacao   = DateTime.Now;
                DateTime dataExpiracao = dataCriacao +
                                         TimeSpan.FromSeconds(tokenConfigurations.Seconds);

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = tokenConfigurations.Issuer,
                    Audience           = tokenConfigurations.Audience,
                    SigningCredentials = signingConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = dataCriacao,
                    Expires            = dataExpiracao
                });
                var token = handler.WriteToken(securityToken);

                return(new
                {
                    authenticated = true,
                    created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                    expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                    accessToken = token,
                    message = "OK"
                });
            }
            else
            {
                return(new
                {
                    authenticated = false,
                    message = "Falha ao autenticar"
                });
            }
        }
 public LoginBusinessImpl(IUserRepository repository, SigningConfigurations signingConfigurations,
                          TokenConfiguration tokenConfiguration)
 {
     this.repository            = repository;
     this.SigningConfigurations = signingConfigurations;
     this.TokenConfiguration    = tokenConfiguration;
 }
Пример #19
0
 public LoginApplication(
     SigningConfigurations signingConfigurations,
     TokenConfiguration tokenConfiguration)
 {
     _signingConfigurations = signingConfigurations;
     _tokenConfiguration    = tokenConfiguration;
 }
        public IActionResult Token(string Login, string Senha)
        {
            try
            {
                // TODO: Deve criar tabela de usuário para validar login/senha
                //  [FromBody]LoginRequest req
                //if (req.Login != "admin" && req.Senha != "admin")
                if (Login != "admin" && Senha != "admin")
                {
                    return(Unauthorized());
                }

                _tokenConfiguration = new TokenConfiguration
                {
                    Audience         = "API",
                    Issuer           = "API",
                    IssuerSigningKey = "7f7ec698-d341-4e19-b6e1-9c70fd3f5df6"
                };

                var authorization = new Authorization(_tokenConfiguration, Login, Senha);
                var token         = authorization.GenerateToken();

                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }));
            }
            catch (Exception ex)
            {
                BadRequest(new { message = ex.Message });
            }

            return(BadRequest());
        }
Пример #21
0
 public LoginController(Microsoft.Extensions.Configuration.IConfiguration configuration,
                        IMyUserService myUserService, IOptions <TokenConfiguration> tokenConfiguration)
 {
     this.configuration      = configuration;
     this.myUserService      = myUserService;
     this.tokenConfiguration = tokenConfiguration.Value;
 }
Пример #22
0
 public UserBusiness(IUserRepository repository, SignInConfiguration signInConfiguration, TokenConfiguration tokenConfiguration)
 {
     _repository          = repository;
     _signInConfiguration = signInConfiguration;
     _tokenConfiguration  = tokenConfiguration;
     _converter           = new UserConverter();
 }
Пример #23
0
 public LoginBusinessImp(IUserRepository repository, SigningConfiguration signingConfiguration,
                         TokenConfiguration tokenConfiguration)
 {
     _repository           = repository;
     _signingConfiguration = signingConfiguration;
     _tokenConfiguration   = tokenConfiguration;
 }
Пример #24
0
        public static ResponseAuthentication GenerateToken(User user, SigningConfiguration signingConfiguration, TokenConfiguration tokenConfiguration)
        {
            _signingConfiguration = signingConfiguration;
            _tokenConfiguration   = tokenConfiguration;

            List <Claim> claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Email),
                new Claim(ClaimTypes.Name, user.Name),
            };

            user.Roles.ForEach(role =>
            {
                claims.Add(new Claim(ClaimTypes.Role, role.Role.ToString()));
            });

            ClaimsIdentity identity = new ClaimsIdentity(
                new GenericIdentity(user.Email),
                claims);

            DateTime createDate     = DateTime.Now;
            DateTime expirationDate = createDate + TimeSpan.FromSeconds(Convert.ToDouble(_tokenConfiguration.Seconds));

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            string token = CreateToken(identity, createDate, expirationDate, handler);


            return(SuccessObject(createDate, expirationDate, token, user));
        }
Пример #25
0
        public static void ConfigToken(IServiceCollection services, IConfiguration Configuration)
        {
            var signingConfiguration = new SigningConfiguration();

            services.AddSingleton(signingConfiguration);

            var tokenConfiguration = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfiguration);
            services.AddSingleton(tokenConfiguration);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions => {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = signingConfiguration.Key;
                paramsValidation.ValidAudience            = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer              = tokenConfiguration.Issuer;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(auth => {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });
        }
Пример #26
0
        public static string GenerateTokenRecoverPassword(User user, SigningConfiguration signingConfiguration, TokenConfiguration tokenConfiguration)
        {
            _signingConfiguration = signingConfiguration;
            _tokenConfiguration   = tokenConfiguration;


            DateTime createDate     = DateTime.Now;
            DateTime expirationDate = createDate + TimeSpan.FromSeconds(Convert.ToDouble(_tokenConfiguration.Seconds));

            List <Claim> claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.NameId, user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Expiration, expirationDate.ToString()),
            };


            ClaimsIdentity identity = new ClaimsIdentity(
                new GenericIdentity(user.Email),
                claims);


            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            return(CreateToken(identity, createDate, expirationDate, handler));
        }
Пример #27
0
        public static void ConfigureDependenciesJwt(IServiceCollection serviceCollection, IConfiguration configuration)
        {
            SigningConfiguration signingConfiguration = new SigningConfiguration();

            serviceCollection.AddSingleton(signingConfiguration);

            TokenConfiguration tokenConfiguration = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(
                configuration.GetSection("TokenConfiguration")).Configure(tokenConfiguration);
            serviceCollection.AddSingleton(tokenConfiguration);


            serviceCollection.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfiguration.Key;
                paramsValidation.ValidAudience    = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer      = tokenConfiguration.Issuer;
            });



            serviceCollection.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            });
        }
Пример #28
0
        public void ConfigureServices(IServiceCollection services)
        {
            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(
                _configuration.GetSection("TokenConfigurations")
                )
            .Configure(tokenConfigurations);

            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddMvc(options =>
            {
                options.RespectBrowserAcceptHeader = true;

                options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("text/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));
            }).AddXmlDataContractSerializerFormatters();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title   = "ASP.NETCore_JWT",
                    Version = "v1"
                });
            });

            services.AddScoped <StoreDataContext, StoreDataContext>();
            services.AddScoped <ILoginRepository, LoginRepositoryImpl>();
            services.AddScoped <ILoginService, LoginServiceImpl>();
        }
Пример #29
0
 public JwtIdentityAuthenticationService(
     SigningConfiguration signingConfiguration,
     TokenConfiguration tokenConfiguration)
 {
     _signingConfiguration = signingConfiguration;
     _tokenConfiguration   = tokenConfiguration;
 }
Пример #30
0
        public static IServiceCollection TokenConfiguration(this IServiceCollection services, IConfiguration configuration)
        {
            var signingCredentials = new SigningConfiguration();

            services.AddSingleton(signingCredentials);

            var tokenConfiguration = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(configuration).Configure(tokenConfiguration);

            services.AddSingleton(tokenConfiguration);

            services.AddAuthentication(authConfig =>
            {
                authConfig.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authConfig.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(bearerOpt =>
            {
                var paramsValidation = bearerOpt.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = new SymmetricSecurityKey(Encoding.
                                                                             ASCII.GetBytes(configuration["TokenConfiguration:Secret"]));
                paramsValidation.ValidAudience            = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer              = tokenConfiguration.Issuer;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });


            services.AddAuthorization(auth =>
            {
                var bearerRequirement        = new BearerRequirement(configuration);
                var administratorRequirement = new AdministratorRequirement(configuration);
                var userRequirement          = new UserRequiriment(configuration);

                var bearerAuthorization = new AuthorizationPolicyBuilder()
                                          .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                          .AddRequirements(bearerRequirement)
                                          .RequireAuthenticatedUser().Build();

                var administratorBearer = new AuthorizationPolicyBuilder()
                                          .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                          .AddRequirements(administratorRequirement)
                                          .RequireAuthenticatedUser().Build();

                var userBearer = new AuthorizationPolicyBuilder()
                                 .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                 .AddRequirements(userRequirement)
                                 .RequireAuthenticatedUser().Build();

                auth.AddPolicy("Bearer", bearerAuthorization);
                auth.AddPolicy("AdministratorBearer", administratorBearer);
                auth.AddPolicy("UserBearer", userBearer);
            });



            return(services);
        }