예제 #1
0
        public void ReturnsJwtSecurityToken()
        {
            const string issuer          = "http://cloudinventory.ru/";
            var          expires         = new DateTime(2018, 5, 3);
            var          jwtTokenOptions = new JwtTokenOptions
            {
                Issuer = issuer
            };
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret key"));
            var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
            var claims = new List <Claim>();

            _mock.Mock <IOptions <JwtTokenOptions> >()
            .Setup(options => options.Value)
            .Returns(jwtTokenOptions);

            _mock.Mock <ISymmetricSecurityKeyProvider>()
            .Setup(provider => provider.GetKey())
            .Returns(symmetricSecurityKey);

            var service = _mock.Create <JwtSecurityTokenProvider>();
            var actual  = service.Create(claims, expires, signingCredentials);

            var expected = new JwtSecurityToken(issuer, issuer, claims, expires: expires,
                                                signingCredentials: signingCredentials);

            ContentAssert.AreEqual(expected, actual);
        }
예제 #2
0
        public void ReturnsExpiresDateForLongTimeToLive()
        {
            var       now        = new DateTime(2018, 5, 3);
            const int timeToLive = 30;

            var jwtTokenOptions = new JwtTokenOptions
            {
                ExpireDaysLongToken = timeToLive
            };

            _mock.Mock <INowProvider>()
            .Setup(provider => provider.Now())
            .Returns(now);

            _mock.Mock <IOptions <JwtTokenOptions> >()
            .Setup(options => options.Value)
            .Returns(jwtTokenOptions);

            var service = _mock.Create <JwtTokenExpireDateTimeProvider>();
            var actual  = service.Get(true);

            var expected = now.AddDays(timeToLive);

            Assert.AreEqual(expected, actual);
        }
예제 #3
0
 static AccountsController()
 {
     JwtBearerOptions                     = new JwtTokenOptions();
     OAuthBearerOptions                   = new OAuthBearerAuthenticationOptions();
     OAuthBearerOptions.Provider          = new TokenProvider();
     OAuthBearerOptions.AccessTokenFormat = new JwtTokenFormat(TimeSpan.FromDays(7));
 }
        public static IServiceCollection SetupJwtAuth(this IServiceCollection services, IConfiguration configuration)
        {
            var tokenOptions = new JwtTokenOptions();

            configuration.Bind("JwtToken", tokenOptions);
            byte[] key = Encoding.ASCII.GetBytes(tokenOptions.Key);

            services
            .Configure <JwtTokenOptions>(configuration.GetSection("JwtToken"))
            .AddScoped <ITokenService, TokenService>()
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ValidAudience            = tokenOptions.Audience,
                    ValidIssuer = tokenOptions.Issuer,
                    ClockSkew   = TimeSpan.Zero
                };
            });
            return(services);
        }
예제 #5
0
        public UsuarioCommandHandler(
            IBus bus,
            IBusMS busMS,
            IUnitOfWork uow,
            IDomainNotificationHandler <DomainNotification> notifications,
            IEventRepository <DomainNotification> dnRepo,
            IUsuarioRepository userRepo,
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            IOptions <JwtTokenOptions> jwtTokenOptions
            //IEmailSender emailSender
            ) : base(bus, uow, notifications)
        {
            _bus      = bus;
            _busMS    = busMS;
            _uow      = uow;
            _dnRepo   = dnRepo;
            _userRepo = userRepo;

            _userManager   = userManager;
            _signInManager = signInManager;
            //_emailSender = emailSender;
            _jwtTokenOptions = jwtTokenOptions.Value;
            //ThrowIfInvalidOptions(_jwtTokenOptions);
        }
예제 #6
0
        public AccountController(
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            IUser user,
            IBus bus,
            IMapper mapper,
            ILogService logService,
            ILoggerFactory loggerFactory,
            IUsuarioService usuarioService,
            IGrupoAcessoService grupoAcessoService,
            IPermissaoService permissaoService,
            IOptions <JwtTokenOptions> jwtTokenOptions,
            IDomainNotificationHandler <DomainNotification> notifications,
            IOptions <AuditConfig> auditConfig,
            Infra.CrossCutting.Identity.Services.IEmailSender emailSender,
            IUsuarioAppService usuarioAppService) : base(notifications, user, bus, auditConfig)
        {
            _usuarioAppService = usuarioAppService;

            _bus                = bus;
            _mapper             = mapper;
            _userManager        = userManager;
            _signInManager      = signInManager;
            _usuarioService     = usuarioService;
            _grupoAcessoService = grupoAcessoService;
            _permissaoService   = permissaoService;
            _emailSender        = emailSender;

            _jwtTokenOptions = jwtTokenOptions.Value;
            ThrowIfInvalidOptions(_jwtTokenOptions);
            _logService = logService;
            _logger     = loggerFactory.CreateLogger <AccountController>();
        }
예제 #7
0
        public static void AddAuthenticationBundle(this IServiceCollection services, Action <JwtTokenOptions> config)
        {
            var options = new JwtTokenOptions();

            services.Configure(config);
            config.Invoke(options);

            var symmetricKey = new SymmetricSecurityKey(options.PrivateKey);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opts =>
            {
                opts.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,

                    ValidIssuer      = options.Issuer,
                    ValidAudience    = options.AccessTokenAudience,
                    IssuerSigningKey = symmetricKey
                };
            });
        }
        public static IServiceCollection AddJwtSimpleServer(this IServiceCollection services, Action <JwtTokenOptions> setup)
        {
            var jwtTokenOptions = new JwtTokenOptions();

            setup(jwtTokenOptions);

            if (string.IsNullOrEmpty(jwtTokenOptions.IssuerSigningKey))
            {
                throw new ArgumentNullException(nameof(jwtTokenOptions.IssuerSigningKey));
            }
            ;

            services.TryAddSingleton <IRefreshTokenStore, NoRefreshTokenStore>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                // Study what will be default implementation and what will be configured by user
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtTokenOptions.ValidIssuer,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenOptions.IssuerSigningKey)),
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

            return(services);
        }
 public JwtTokenExpireDateTimeProvider(
     IOptions <JwtTokenOptions> options,
     INowProvider nowProvider)
 {
     _nowProvider = nowProvider;
     _options     = options.Value;
 }
        public static AuthenticationBuilder AddJwtBearerAuthentication(this IServiceCollection services, Action <JwtTokenOptions> options)
        {
            var optInstance = new JwtTokenOptions();

            options(optInstance);

            services.AddSingleton(optInstance);
            services.AddTransient <IJwtTokenService, JwtTokenService>();

            return(services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = optInstance.ValidateAudience,
                    ValidateIssuer = optInstance.ValidateIssuer,
                    ValidateIssuerSigningKey = optInstance.ValidateIssuerSigningKey,
                    ValidateLifetime = optInstance.ValidateLifetime,
                    IssuerSigningKey = optInstance.SecurityKey
                };
            }));
        }
예제 #11
0
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;

            _jwtOptions = new JwtTokenOptions();
            configuration.Bind("JwtToken", _jwtOptions);
        }
 public TokenValidationParametersProvider(
     IOptions <JwtTokenOptions> options,
     ISymmetricSecurityKeyProvider symmetricSecurityKeyProvider)
 {
     _symmetricSecurityKeyProvider = symmetricSecurityKeyProvider;
     _options = options.Value;
 }
예제 #13
0
        public void ReturnsTokenValidationParameters()
        {
            const string issuer = "http://cloudinventory.ru/";

            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret key"));

            var jwtTokenOptions = new JwtTokenOptions
            {
                Issuer = issuer
            };

            _mock.Mock <IOptions <JwtTokenOptions> >()
            .Setup(options => options.Value)
            .Returns(jwtTokenOptions);

            _mock.Mock <ISymmetricSecurityKeyProvider>()
            .Setup(provider => provider.GetKey())
            .Returns(symmetricSecurityKey);

            var service = _mock.Create <TokenValidationParametersProvider>();
            var actual  = service.GetParameters();

            var expected = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = issuer,
                ValidAudience    = issuer,
                IssuerSigningKey = symmetricSecurityKey
            };

            ContentAssert.AreEqual(expected, actual);
        }
 public UsersController(IUserService userService, IPlayerService playerService, ICityService cityService, ITokenService tokenService, IOptions <JwtTokenOptions> jwtTokenOptions)
 {
     _userService     = userService;
     _playerService   = playerService;
     _cityService     = cityService;
     _tokenService    = tokenService;
     _jwtTokenOptions = jwtTokenOptions.Value;
 }
예제 #15
0
 public JwtAuthorizeService(
     IOptions <JwtTokenOptions> JwtTokenOptions,
     UserManager <CustomIdentityUser> userManager,
     AuthDbContext authDbContext)
 {
     jwtTokenOptions = JwtTokenOptions.Value;
     _userManager    = userManager;
     _authDbContext  = authDbContext;
 }
예제 #16
0
        public JwtTokenIdentityService(UserManager <ApplicationUser> userManager,
                                       SignInManager <ApplicationUser> signInManager, IMapper mapper,
                                       IConfiguration configuration)
        {
            _userManager   = userManager;
            _signInManager = signInManager;
            _mapper        = mapper;

            _options = new JwtTokenOptions();
            configuration.GetSection(JwtTokenOptions.SectionName).Bind(_options);
        }
예제 #17
0
 public AuthController(IJwtTokenBuilder tokenBuilder,
                       IOptions <JwtTokenOptions> jwtOptions,
                       UserManager <IdentityUser> userManager,
                       SignInManager <IdentityUser> signInManager,
                       Tenants tenants)
 {
     _tokenBuilder  = tokenBuilder;
     _jwtOptions    = jwtOptions.Value;
     _userManager   = userManager;
     _signInManager = signInManager;
     _tenants       = tenants;
 }
예제 #18
0
        public AccountController(
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            IOptions <JwtTokenOptions> jwtTokenOptions,
            IUser user
            ) : base(user)
        {
            _userManager     = userManager;
            _signInManager   = signInManager;
            _jwtTokenOptions = jwtTokenOptions.Value;

            ThrowIfInvalidOptions(_jwtTokenOptions);
        }
예제 #19
0
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     IOptions <JwtTokenOptions> JwtTokenOptions,
     IEmailSender emailSender,
     ILogger <AccountController> logger)
 {
     _userManager     = userManager;
     _signInManager   = signInManager;
     _emailSender     = emailSender;
     _logger          = logger;
     _jwtTokenOptions = JwtTokenOptions.Value;
 }
예제 #20
0
    public static IServiceCollection AddAnetJwt <TAuthenticator, TRefreshTokenStore>(
        this IServiceCollection services,
        Action <JwtTokenOptions> configure,
        Action <JwtBearerOptions> configureJwtBearer = null)
        where TAuthenticator : class, IAuthenticator
        where TRefreshTokenStore : class, IRefreshTokenStore
    {
        var options = new JwtTokenOptions();

        configure(options);

        ArgumentNullException.ThrowIfNull(options);
        ArgumentNullException.ThrowIfNull(options.Key);

        services.AddSingleton(options);
        services.AddHttpContextAccessor();
        services.AddTransient <JwtProvider>();
        services.AddTransient <IAuthenticator, TAuthenticator>();
        services.AddTransient <IRefreshTokenStore, TRefreshTokenStore>();
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(jwtBearerOptions =>
        {
            jwtBearerOptions.TokenValidationParameters = new()
            {
                ValidIssuer              = options.Issuer,
                ValidateIssuer           = !string.IsNullOrEmpty(options.Issuer),
                ValidAudience            = options.Audience,
                ValidateAudience         = !string.IsNullOrEmpty(options.Audience),
                ValidateLifetime         = options.Expiration > 0,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Key)),
            };
            jwtBearerOptions.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    context.Token = context.Request.Cookies[options.FallbackCookieKey];
                    return(Task.CompletedTask);
                }
            };
            configureJwtBearer?.Invoke(jwtBearerOptions);
        });

        return(services);
    }
        public AccountController(
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            ILoggerFactory loggerFactory,
            IOptions <JwtTokenOptions> jwtTokenOptions,
            IUsuarioDadosAppService usuarioDadosAppService)
        {
            _userManager            = userManager;
            _signInManager          = signInManager;
            _usuarioDadosAppService = usuarioDadosAppService;
            _jwtTokenOptions        = jwtTokenOptions.Value;

            ThrowIfInvalidOptions(_jwtTokenOptions);
            _logger = loggerFactory.CreateLogger <AccountController>();
        }
예제 #22
0
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     ILoggerFactory loggerFactory,
     IOptions <JwtTokenOptions> jwtTokenOptions,
     INotificationHandler <NotificacaoDominio> notifications,
     IUsuario user,
     IMediatorHandler mediator) : base(notifications, user, mediator)
 {
     _userManager     = userManager;
     _signInManager   = signInManager;
     _mediator        = mediator;
     _jwtTokenOptions = jwtTokenOptions.Value;
     ThrowIfInvalidOptions(_jwtTokenOptions);
     _logger = loggerFactory.CreateLogger <AccountController>();
 }
예제 #23
0
        public JwtTokenController(IOptions <JwtTokenOptions> tokenOptions,
                                  ILoggerFactory loggerFactory,
                                  AhvalDbContext databaseContext)
        {
            jwtTokenOptions = tokenOptions.Value;
            ThrowIfInvalidOptions(jwtTokenOptions);

            logger = loggerFactory.CreateLogger <JwtTokenController>();

            serializerSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            };

            db = databaseContext;
        }
        public AccountController(IDomainNotificationHandler <DomainNotification> notifications,
                                 IUser user,
                                 UserManager <ApplicationUser> userManager,
                                 SignInManager <ApplicationUser> signInManager,
                                 ILoggerFactory loggerFactory,
                                 IBus bus,
                                 IOptions <JwtTokenOptions> jwtTokenOptions) : base(notifications, user, bus)
        {
            _userManager     = userManager;
            _signInManager   = signInManager;
            _bus             = bus;
            _jwtTokenOptions = jwtTokenOptions.Value;

            ThrowIfInvalidOptions(_jwtTokenOptions);
            _logger = loggerFactory.CreateLogger <AccountController>();
        }
예제 #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var jwtOptions = new JwtTokenOptions(Configuration);

            app.UseJwtBearerAuthentication(jwtOptions);

            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(s =>
            {
                s.SwaggerEndpoint("/swagger/v1/swagger.json", "Stone  API v1.0");
            });
        }
예제 #26
0
        private static TokenValidationParameters GetTokenValidationParameters(IConfiguration configuration)
        {
            var tokenOptions = new JwtTokenOptions();

            configuration.GetSection(JwtTokenOptions.SectionName).Bind(tokenOptions);

            var bytesKey     = Encoding.UTF8.GetBytes(tokenOptions.Key);
            var symmetricKey = new SymmetricSecurityKey(bytesKey);

            return(new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = symmetricKey,
                ValidateIssuer = false,
                ValidateAudience = false
            });
        }
예제 #27
0
        private static TokenValidationParameters CreateTokenValidationParameters(IConfiguration configuration)
        {
            var jwtTokenOptions = new JwtTokenOptions();

            configuration.GetSection(nameof(JwtTokenOptions)).Bind(jwtTokenOptions);

            return(new TokenValidationParameters
            {
                IssuerSigningKey =
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtTokenOptions.Key)),
                ValidAudience = jwtTokenOptions.Audience,
                ValidateIssuerSigningKey = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidIssuer = jwtTokenOptions.Issuer
            });
        }
예제 #28
0
 public AutenticacaoController(
     IConfiguration config,
     IUsuarioRepository usuarioRepository,
     IEmpresaRepository empresaRepository,
     IClienteRepository clienteRepository,
     IOptions <JwtTokenOptions> jwtTokenOptions,
     INotificationHandler <DomainNotification> notifications,
     IUser user,
     IMediatorHandler mediator) : base(notifications, user, mediator)
 {
     Configuration      = config;
     _usuarioRepository = usuarioRepository;
     _empresaRepository = empresaRepository;
     _jwtTokenOptions   = jwtTokenOptions.Value;
     _clienteRepository = clienteRepository;
     _mediator          = mediator;
     ThrowIfInvalidOptions(_jwtTokenOptions);
 }
예제 #29
0
        public void CreateaNetworkInstance()
        {
            NetworkHealthCheck check = new NetworkHealthCheck(connectionString);

            var a1 = new NetworkHealthCheck("google.com:443");

            var a2 = new HttpCallRequestModel
            {
                Url                 = "",
                Method              = "",
                BearerToken         = "",
                Base64Certificate   = "",
                CertificatePassword = "",
                SubscriptionKey     = "",
                IsResponseJson      = false
            };
            var a3 = new HttpCallRespondModel
            {
                RequestModel = a2,
                // StatusCode= HttpStatusCode.OK,
                Responsetext    = "",
                ErrorMessage    = "",
                ProcessMessages = "",
                // ResponseMessage= new HttpResponseMessage()
            };

            var a4 = new JwtTokenOptions
            {
                AuthorityUrl = "",
                UserName     = "",
                Password     = "",
                ClientId     = ""
            };

            var a5 = new HttpClientOptions
            {
                BaseAddress             = "",
                DefaultRequestHeaders   = new Dictionary <string, string>(),
                RequestContentType      = "",
                ClientCertificateBase64 = "",
                CertificateThumbprint   = "",
                JwtTokenOptions         = a4,
            };
        }
예제 #30
0
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member

        #endregion

        #region Construtores

        /// <summary>
        /// Cria uma nova instância da API
        /// </summary>
        public UsuarioController
        (
            IUsuarioAppService appService,
            IHostingEnvironment hostingEnvironment,
            IOptions <JwtTokenOptions> jwtTokenOptions,
            IAppUser usuario
        )
        {
            _jwtTokenOptions    = jwtTokenOptions.Value;
            _appService         = appService;
            _hostingEnvironment = hostingEnvironment;
            _usuario            = usuario;

            IConfigurationBuilder builder = new ConfigurationBuilder()
                                            .SetBasePath(Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json");

            Configuration = builder.Build();
        }