Ejemplo n.º 1
0
 public AccountController(UserManager <User> userManager, SignInManager <User> signInManager, IFileLogger fileLogger, IJwtSettings jwtSettings)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _fileLogger    = fileLogger;
     _jwtSettings   = jwtSettings;
 }
 public JwtTokenGenerator(
     IIdentityResolver identityResolver,
     IJwtSettings settings)
 {
     _settings         = settings;
     _identityResolver = identityResolver;
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Extensão para configurar autenticação e autorização
        /// </summary>
        /// <param name="services">Auto referencia para a coleção de seviços</param>
        /// <returns></returns>
        public static IServiceCollection ConfigureDefaultAuthService(
            this IServiceCollection services)
        {
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            IJwtSettings     jwt     = serviceProvider.GetRequiredService <IJwtSettings>();
            IGeneralSettings general = serviceProvider.GetRequiredService <IGeneralSettings>();

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(general.DefaultEncoding.GetBytes(jwt.IssuerSigningKey)),
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ClockSkew     = TimeSpan.Zero,
                    ValidIssuer   = jwt.ValidIssuer,
                    ValidAudience = jwt.ValidAudience
                };
            });

            return(services);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Executed on invocation
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userService"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, IUserService userService, IJwtSettings jwtSettings)
        {
            //Reading the AuthHeader which is signed with JWT
            string token = context.GetAuthorizationHeader();

            if (token != null)
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Convert.FromBase64String(jwtSettings.Secret);
                var jwtToken     = new JwtSecurityToken();

                //If validate token fails then jwt Token is inválid
                try
                {
                    tokenHandler.ValidateToken(token, new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = new SymmetricSecurityKey(key),
                        ValidateIssuer           = false,
                        ValidateAudience         = false,
                        ValidateLifetime         = true,
                        // Set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                        ClockSkew = TimeSpan.Zero
                    }, out SecurityToken validatedToken);

                    jwtToken = (JwtSecurityToken)validatedToken;
                }
                catch
                {
                    jwtToken = null;
                }

                if (jwtToken != null)
                {
                    var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "Id").Value);

                    var user = await userService.LoadAsync(userId);

                    // Attach user to context on successful jwt validation
                    //context.Items["User"] = user;


                    // Identity Principal
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.AuthenticationMethod, "Jwt"),
                        new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                        new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName),
                        new Claim(ClaimTypes.Email, user.Email)
                    };

                    var identity = new ClaimsIdentity(claims, "Basic");
                    context.User = new ClaimsPrincipal(identity);
                }
            }

            //Pass to the next middleware
            await _next(context);
        }
 public UserController(UserManager <ApplicationUser> userManager,
                       SignInManager <ApplicationUser> signInManager,
                       IJwtSettings jwtSettings)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _jwtSettings   = jwtSettings;
 }
Ejemplo n.º 6
0
 public JwtService(
     IJwtSettings jwtSettings,
     IClaimsService claimsService
     )
 {
     _jwtSettings   = jwtSettings;
     _claimsService = claimsService;
 }
        public static void AddFluffySpoonJwt <TIdentityResolver>(
            this IServiceCollection services,
            IJwtSettings jwtSettings) where TIdentityResolver : class, IIdentityResolver
        {
            services.AddScoped <IIdentityResolver, TIdentityResolver>();
            services.AddScoped <IJwtTokenGenerator, JwtTokenGenerator>();

            services.AddSingleton(jwtSettings);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = SigningKeyHelper.GenerateKeyFromSecret(jwtSettings.SecretKey),
                ValidateIssuer           = true,
                ValidIssuer      = jwtSettings.Issuer,
                ValidateAudience = true,
                ValidAudience    = jwtSettings.Audience,
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero
            };

            services
            .AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options => {
                options.SaveToken = false;
                options.TokenValidationParameters = tokenValidationParameters;
                options.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = (context) =>
                    {
                        if (context.HttpContext.Items.ContainsKey(Constants.MiddlewareTokenPassingKey))
                        {
                            context.Token = (string)context.HttpContext.Items[Constants.MiddlewareTokenPassingKey];
                        }

                        if (context.Request.Query.ContainsKey("access_token"))
                        {
                            var path = context.HttpContext.Request.Path;
                            if (!string.IsNullOrEmpty(context.Request.Query["access_token"]))
                            {
                                context.Token = context.Request.Query["access_token"];
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };
            });
        }
Ejemplo n.º 8
0
 public AccountsController(
     IAccountService accountService,
     IMapperFactory mapperFactory,
     IJwtService jwtService,
     IEmailService emailService,
     IJwtSettings jwtSettings
     )
 {
     _accountService = accountService;
     _jwtService     = jwtService;
     _mapper         = mapperFactory.GetMapper(typeof(WebServices).Name);
     _emailService   = emailService;
     _jwtSettings    = jwtSettings;
 }
Ejemplo n.º 9
0
        public IdentityService(IJwtSettings jwtSettings, IMongoSettings settings
                               , ConvertModelsService convertModelsService)
        {
            _jwtSecret = jwtSettings.Secret;

            var client   = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _users = database.GetCollection <BackendUserModel>("Users");

            var redis = RedisSettings.GetConnectionMultiplexer();

            _redisUsersDatabase = redis.GetDatabase(0);

            _convertModelsService = convertModelsService;
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Construtor padrão
 /// </summary>
 /// <param name="encryption">Objeto de criptografia</param>
 /// <param name="userBusiness">Negócios para usuários</param>
 /// <param name="general">Configurações gerais</param>
 /// <param name="jwt">Configurações JWT</param>
 /// <param name="emailSender">Envio de email</param>
 /// <param name="messageTemplate">Template para mensagens</param>
 /// <param name="authUser">Usuário autenticado</param>
 /// <param name="logger">Logger</param>
 public AuthBusiness(
     IEncryption encryption,
     IUserBusiness userBusiness,
     IGeneralSettings general,
     IJwtSettings jwt,
     IEmailSender emailSender,
     IMessageTemplate messageTemplate,
     IAuthUser authUser,
     ILogger <AuthBusiness> logger)
 {
     _encryption      = encryption;
     _userBusiness    = userBusiness;
     _general         = general;
     _jwt             = jwt;
     _emailSender     = emailSender;
     _messageTemplate = messageTemplate;
     _authUser        = authUser;
     _logger          = logger;
 }
Ejemplo n.º 11
0
 public UsersController(
     IAccountService accountService,
     IEventService eventService,
     IMapperFactory mapperFactory,
     IJwtService jwtService,
     IEmailService emailService,
     ILogger <AccountsController> logger,
     IImageSettings accountImageSettings,
     IUtilityService utilityService,
     IJwtSettings jwtSettings
     )
 {
     _accountService       = accountService;
     _eventService         = eventService;
     _jwtService           = jwtService;
     _mapper               = mapperFactory.GetMapper(typeof(WebServices).Name);
     _logger               = logger;
     _emailService         = emailService;
     _accountImageSettings = accountImageSettings;
     _utilityService       = utilityService;
     _jwtSettings          = jwtSettings;
 }
 public AuthController(EffortlessContext context, IJwtSettings jwtSettings, IMapper mapper)
 {
     _unitOfWork  = new UnitOfWork(context);
     _jwtSettings = jwtSettings;
     _mapper      = mapper;
 }
Ejemplo n.º 13
0
 public JwtTokenHelper(IJwtSettings jwtSettings)
 {
     this.jwtSettings = jwtSettings;
 }
Ejemplo n.º 14
0
 public JwtService(IJwtSettings settings, IHttpContextAccessor httpContextAccessor)
 {
     _jwtSettings         = settings;
     _httpContextAccessor = httpContextAccessor;
 }
Ejemplo n.º 15
0
 public AccountService(ApiContext apiContext, IJwtSettings jwtSettings)
 {
     _apiContext  = apiContext;
     _jwtSettings = jwtSettings;
 }
Ejemplo n.º 16
0
 public JwtService(IJwtSettings jwtSettings)
 {
     _jwtSettings = jwtSettings;
 }
Ejemplo n.º 17
0
 public UserLoginCommandHandler(IMongoDbRepository <User> userRepository, IJwtSettings jwtSettings, ICacheService cacheService)
 {
     _userRepository = userRepository;
     _jwtSettings    = jwtSettings;
     _cacheService   = cacheService;
 }
Ejemplo n.º 18
0
 public TokenService(IOptionsSnapshot <JwtSettings> jwtSettings)
 {
     _jwtSettings = jwtSettings.Value;
     _key         = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_jwtSettings.Secret));
 }
Ejemplo n.º 19
0
 public EmailClaimsService(
     IJwtSettings jwtSettings
     ) : base(jwtSettings)
 {
 }
Ejemplo n.º 20
0
 public JwtService(IJwtSettings jwtSettings)
 {
     this.jwtSettings = jwtSettings;
 }
Ejemplo n.º 21
0
 public ClaimsService(
     IJwtSettings jwtSettings
     )
 {
     _jwtSettings = jwtSettings;
 }
Ejemplo n.º 22
0
        public void GenerateJwtToken_Should_Return_Null_With_Missing_Or_Empty_JwtSettings_Info(IJwtSettings settings)
        {
            JwtTokenHelper helper = new JwtTokenHelper(settings);
            var            token  = helper.GenerateJwtToken(sampleUser);

            Assert.Null(token);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="jwtSettings"></param>
 /// <exception cref="ArgumentNullException"></exception>
 public JwtService(IJwtSettings jwtSettings, IRedisCacheService cacheService)
 {
     _jwtSettings  = jwtSettings ?? throw new ArgumentNullException(nameof(jwtSettings));
     _cacheService = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
 }
Ejemplo n.º 24
0
 public TokenService(IJwtSettings settings)
 {
     _settings = settings;
 }