Пример #1
0
        public object Login([FromServices] JwtConfiguration tokenConfigurations, [FromBody] LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(GetErros());
            }

            string token = string.Empty;

            var user = UserRepositoryMock.GetUser(model.Username, model.Password);

            if (user != null)
            {
                token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(tokenConfigurations.JwtKey))
                        .AddSubject(user.Name)
                        .AddIssuer(tokenConfigurations.Issuer)
                        .AddAudience(tokenConfigurations.Audience)
                        .AddNameId(user.Username)
                        .AddExpiryDays(tokenConfigurations.Days)
                        //Adicionado um claim com os perfis de uso.
                        .AddClaimsPermission(user.Permissions)
                        .Build();

                return(new { token });
            }
            else
            {
                return(BadRequest(
                           new { message = "Usuário ou senha inválidos!" }
                           ));
            }
        }
 private JwtSecurityToken GenerateJwt(JwtConfiguration jwtConfiguration, ISecurityKeyGenerator keyGenerator, ICollection <Claim> claims)
 {
     return(new JwtSecurityToken(issuer: jwtConfiguration.Issuer,
                                 audience: jwtConfiguration.MobileAudience,
                                 claims: claims,
                                 signingCredentials: new SigningCredentials(keyGenerator.Generate(jwtConfiguration.Key), jwtConfiguration.SecurityAlgorithm)));
 }
Пример #3
0
        public void Should_BuildToken()
        {
            //Arrange

            var user = new UserLogin
            {
                Id    = 1,
                Name  = "User 1",
                Email = "*****@*****.**",
                Roles = new List <string> {
                    "Admin"
                }
            };

            var jwtConfigurations = new JwtConfiguration
            {
                Key = "this is a key very secret"
            };

            _jwtOptionsMock.Setup(x => x.Value)
            .Returns(jwtConfigurations);


            _service = new LoginService(_jwtOptionsMock.Object);

            //Act

            var token = _service.BuildToken(user);

            //Assert

            Assert.False(string.IsNullOrEmpty(token));
        }
Пример #4
0
        /// <summary>
        /// Builds the token used for authentication
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public string BuildToken(User user, string role)
        {
            JwtConfiguration jwtConfig = _config.GetSection("Jwt").Get<JwtConfiguration>();

            // Create a claim based on the users emai. You can add more claims like ID's and any other info
            Claim[] claims = new[] {
                  new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                  new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                  new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                  new Claim(JwtRegisteredClaimNames.Email, user.Email),
                  new Claim(ClaimTypes.Role, role)
            };

            // Creates a key from our private key that will be used in the security algorithm next
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key));

            // Credentials that are encrypted which can only be created by our server using the private key
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // this is the actual token that will be issued to the user
            JwtSecurityToken token = new JwtSecurityToken(jwtConfig.Issuer,
                jwtConfig.Audience,
                claims,
                expires: DateTime.Now.AddMinutes(double.Parse(jwtConfig.ExpireTime)),
                signingCredentials: creds);

            // return the token in the correct format using JwtSecurityTokenHandler
            return tokenHandler.WriteToken(token);
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //CONFIGURACIÓN NECESARIA PARA INDICAR LA VERSIÓN DE MVC A UTILIZAR
            services.AddMvc(options =>
            {
                // Cambios para que se lean correctamente las fechas UTC-0 desde la URL
                options.ModelBinderProviders.Insert(0, new UtcDateTimeModelBinderProvider());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(jsonOptions =>
            {
                jsonOptions.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            });

            // SE AGREGA LA LÓGICA PARA REALIZAR AUTORIZACIÓN BASADA EN PERMISOS
            var noAuthenticatedUserByPassAuthorization = configuration.GetValue <bool>("NoAuthenticatedUserByPassAuthorization");

            services.AddPermissionBasedAuthorization(noAuthenticatedUserByPassAuthorization);

            // SE AGREGA LA AUTENTICACIÓN BASADA EN JWT
            var jwtConfigurationSection = configuration.GetSection("Jwt");
            var secretKey        = jwtConfigurationSection.GetValue <string>("SecretKey");
            var expireDays       = jwtConfigurationSection.GetValue <int>("ExpireDays");
            var jwtConfiguration = new JwtConfiguration(secretKey, expireDays);

            services.AddSingleton <JwtConfiguration>(jwtConfiguration);
            services.AddJwtBasedAuthentication(jwtConfiguration);

            // SE AGREGAN LAS DEPENDENCIAS PROPIAS DEL DEL NEGOCIO DE LA APLICACIÓN
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            services.AddBusinessDependencies(connectionString);
        }
Пример #6
0
        public JwtAuthService(ILoggerFactory loggerFactory, IOptions <JwtConfiguration> config,
                              IUserRepository users, ICryptoMan crypto)
        {
            _logger = loggerFactory.CreateLogger <JwtAuthService>();
            _config = config.Value;
            _users  = users;

            Crypto = crypto;

            _logger.LogInformation("Generating signing credentials with " + _config.Algorithm);
            _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config.Secret));
            _config.SigningCredentials = new SigningCredentials(_signingKey, _config.Algorithm);

            ThrowIfInvalidOptions(_config);

            _logger.LogInformation("Issuer: " + _config.Issuer
                                   + ", Audience: " + _config.Audience
                                   + ", token validFor timeframe: " + _config.ValidFor);

            ValidationParams = new TokenValidationParameters {
                ValidateIssuer = true,
                ValidIssuer    = _config.Issuer,

                ValidateAudience = true,
                ValidAudience    = _config.Audience,

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,

                RequireExpirationTime = true,
                ValidateLifetime      = true,

                ClockSkew = TimeSpan.Zero
            };
        }
Пример #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext <DataContext>(options =>
                                                options.UseNpgsql(_utilities.GetConnectionString(Configuration)));

            // ASP.NET Core Identity
            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores <DataContext>()
            .AddDefaultTokenProviders();

            // JSON Web Token
            var jwtConfiguration = new JwtConfiguration(services);

            jwtConfiguration.Configure(Configuration.GetSection("AppSettings"));

            services.AddScoped <LineService>();
            services.AddScoped <CompaniesService>();

            // AutoMapper
            var mapper = new MapperConfiguration(config =>
                                                 config.AddProfile <LineModelToDTO>()
                                                 );

            services.AddCors(_utilities.SetCorsPolicy);
            services.AddSingleton(mapper.CreateMapper());
        }
Пример #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            //configuração de CORS
            CorsConfiguration.UseCors(app);

            //configuração do JWT
            JwtConfiguration.UseJwt(app);

            //configuração do swagger
            SwaggerConfiguration.UseSwagger(app);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Пример #9
0
 public Startup(IConfiguration configuration)
 {
     Configuration         = configuration;
     JwtConfiguration      = Configuration.GetSection("Bearer").Get <JwtConfiguration>();
     PasswordConfiguration = Configuration.GetSection("Password").Get <PasswordConfiguration>();
     Jobs = Configuration.GetSection("Schedules").Get <Dictionary <string, JobConfiguration> >();
 }
Пример #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Setup para configuração do Swagger
            SwaggerConfiguration.AddSwagger(services);

            //Setup para configuração do EntityFramework
            EntityFrameworkConfiguration.AddEntityFramework(services, Configuration);

            //Setup para configuração do JWT
            JwtConfiguration.ConfigureServices(services, Configuration);

            //Setup para o MongoDB
            MongoDBConfiguration.AddMongoDBSetup(services, Configuration);

            //Injeção de dependência
            DependencyInjectionConfiguration.AddDependencyInjection(services);

            //Setup para o MediatR
            MediatRConfiguration.AddMediatRSetup(services);

            //Setup para o AutoMapper
            AutoMapperConfiguration.AddAutoMapperSetup(services);

            //Setup para o CORS
            CorsConfiguration.AddCors(services);
        }
Пример #11
0
 public AuthenticationService(IOptions <JwtConfiguration> jwtSettings,
                              UserManager <ApiUser> userManager)
 {
     _jwtSettings             = jwtSettings.Value;
     _jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
     _userManager             = userManager;
 }
Пример #12
0
        public static IServiceProvider Resolve()
        {
            var serviceProvider = new ServiceCollection();
            var jwtConfig       = new JwtConfiguration
            {
                Secret        = "9ce891b219b6fb5b0088e3e05e05baf5",
                TokenLifetime = TimeSpan.FromMinutes(5),
                Issuer        = "UnitTest",
                Audience      = "UnitTest"
            };

            serviceProvider.AddDbContext <AppIdentityDbContext>(options =>
                                                                options.UseInMemoryDatabase(
                                                                    Guid.NewGuid().ToString()),
                                                                ServiceLifetime.Singleton);

            serviceProvider
            .AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <AppIdentityDbContext>()
            .AddDefaultTokenProviders();

            serviceProvider.AddLogging();
            serviceProvider.AddSingleton(jwtConfig);
            serviceProvider.AddSingleton <IIdentityService, Domain.Services.IdentityService>();

            return(serviceProvider
                   .BuildServiceProvider()
                   .SeedDbTest());
        }
Пример #13
0
        public TokenHelperTest()
        {
            var scopedServices = ServicesResolver.Resolve();

            _jwtConfig   = scopedServices.GetRequiredService <JwtConfiguration>();
            _userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >();
        }
Пример #14
0
        public static IServiceCollection AddAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            var jwtConfiguration = new JwtConfiguration();

            configuration.GetSection(nameof(JwtConfiguration)).Bind(jwtConfiguration);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtConfiguration.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = jwtConfiguration.AudienceId,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(jwtConfiguration.GetAudienceSecretBytes())
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            return(services);
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <Context>(options =>
                                            options.UseSqlServer(Configuration.GetConnectionString("Connection")));

            IdentityConfiguration.AddIdentity(services);
            services.AddCors();
            services.AddMvc();


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <UrlResolver>();
            IdentityConfiguration.ConfigureIdentity(services);

            services.AddSingleton(_ => Configuration as IConfigurationRoot);
            services.AddScoped <PasswordHasher <User> >();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IEventRepository, EventRepository>();
            services.AddScoped <IEventService, EventService>();
            services.AddScoped <IStatusService, StatusService>();
            services.AddScoped <IStatusRepository, StatusRepository>();
            services.AddScoped <ICommentRepository, CommentRepository>();
            services.AddScoped <ICommentService, CommentService>();
            services.AddScoped <IUserService, UserService>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "CoolMeet API", Version = "v1"
                });
            });
            services.AddAutoMapper();

            JwtConfiguration.AddJwtAuthorization(Configuration, services);
        }
Пример #16
0
 public UserController(IUserService userService, SignInManager <User> signInManager, JwtConfiguration jwtConfiguration, IRoundService roundService)
 {
     _userService      = userService;
     _roundService     = roundService;
     _signInManager    = signInManager;
     _jwtConfiguration = jwtConfiguration;
 }
Пример #17
0
 public IdentityService(
     JwtConfiguration jWTConfiguration,
     IConfiguration configuration)
 {
     _jWTConfiguration = jWTConfiguration;
     _configuration    = configuration;
 }
Пример #18
0
        private static void ConfigureAuthentication(IServiceCollection services, IConfiguration configuration)
        {
            var jwtSection       = configuration.GetSection("Jwt");
            var jwtConfiguration = new JwtConfiguration(jwtSection["Issuer"], jwtSection["Key"]);

            services.AddSingleton(jwtConfiguration);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = new SymmetricSecurityKey(jwtConfiguration.Key),
                    ValidIssuer              = jwtConfiguration.Issuer,
                    ValidAudience            = jwtConfiguration.Issuer,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                };
            });

            services.AddMvc();
        }
Пример #19
0
 public AccountController(IOptions <JwtConfiguration> jwtConfiguration, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager, ILogger <AccountController> logger)
 {
     _jwtConfiguration = jwtConfiguration.Value;
     _userManager      = userManager;
     _roleManager      = roleManager;
     _logger           = logger;
 }
Пример #20
0
        public async Task <IActionResult> LoginAsync(
            [FromBody] AuthLoginRequest request,
            [FromServices] JwtConfiguration jwtConfiguration)
        {
            try
            {
                var identityUser = await _identityUserManager.FindByNameAsync(request.Username);

                if (identityUser is null)
                {
                    return(NotFound());
                }

                var signInResult = await _signInManager.PasswordSignInAsync(
                    identityUser,
                    request.Password,
                    isPersistent : false,
                    lockoutOnFailure : false);

                if (!signInResult.Succeeded)
                {
                    return(BadRequest());
                }

                var chatUser = await _chatUserManager.GetUserAsync(request.Username);

                var jwtConfig = jwtConfiguration.GetSchemeConfig(JwtSchemes.User);
                var jwtClaims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, chatUser !.Id.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, request.Username),
                };
                var signingCredentials = new SigningCredentials(
                    key: jwtConfig.SecurityKey,
                    algorithm: JwtConfiguration.SecurityAlgorithm
                    );
                var createdAt   = DateTime.UtcNow;
                var validBefore = createdAt.AddMinutes(5);
                var token       = new JwtSecurityToken(
                    issuer: jwtConfig.Issuer,
                    audience: jwtConfig.Audience,
                    claims: jwtClaims,
                    notBefore: createdAt,
                    expires: validBefore,
                    signingCredentials: signingCredentials);

                return(new JsonResult(new AuthLoginResponse(
                                          userId: chatUser !.Id,
                                          auth: new AuthTokenResponse(
                                              accessToken: new JwtSecurityTokenHandler().WriteToken(token),
                                              createdAt: createdAt.ToString("o"),
                                              validBefore: validBefore.ToString("o")))));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Login failed.");
                return(BadRequest("Could not complete login."));
            }
        }
Пример #21
0
        public static async Task <AuthenticationResult> GenerateAuthResultForUserAsync(
            ApplicationUser user, JwtConfiguration jwtConfig,
            UserManager <ApplicationUser> userManager)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(jwtConfig.Secret);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                new Claim(JwtRegisteredClaimNames.Email, user.Email)
            };

            var userClaims = await userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);

            var userRoles = await userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                var role = await userManager.FindByNameAsync(userRole);

                if (role == null)
                {
                    continue;
                }
                var roleClaims = await userManager.GetClaimsAsync(role);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.Add(jwtConfig.TokenLifetime),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                Issuer             = jwtConfig.Issuer,
                Audience           = jwtConfig.Audience
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(new AuthenticationResult
            {
                Success = true,
                Token = tokenHandler.WriteToken(token)
            });
        }
Пример #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("10.0.0.100"));
            });

            //Configure loging
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .WriteTo.Console()
                         .CreateLogger();
            services.AddSingleton(Log.Logger);

            //Configure db context
            EntityFrameworkConfiguration.ConfigureService(services, Configuration);

            //Add auto mapper on start up
            services.AddAutoMapper(typeof(Startup));

            //Configure dependency injection
            IocContainerConfiguration.ConfigureService(services);

            //Configure jwt
            JwtConfiguration.ConfigureService(services, Configuration);
            // Configure your policies
            services.AddAuthorization(options =>
            {
                options.AddPolicy(nameof(Role.SuperAdmin),
                                  policy => policy.RequireClaim(nameof(Role.SuperAdmin)));

                options.AddPolicy(nameof(Role.Administrator),
                                  policy => policy.RequireClaim(nameof(Role.Administrator)));

                options.AddPolicy(nameof(Role.User),
                                  policy => policy.RequireClaim(nameof(Role.User)));
            });

            // Configure action filter attribute
            services.AddControllers(opt =>
            {
                opt.Filters.Add(typeof(ValidateModel));
            });

            // Configure enforce lowercase routing
            services.AddRouting(options => options.LowercaseUrls = true);

            SwaggerConfiguration.ConfigureService(services);

            // Config for upload file
            services.Configure <FormOptions>(o => {
                o.ValueLengthLimit         = int.MaxValue;
                o.MultipartBodyLengthLimit = int.MaxValue;
                o.MemoryBufferThreshold    = int.MaxValue;
            });

            // Config Api Version
            services.AddApiVersioning();
        }
Пример #23
0
 public void Setup()
 {
     _userManager       = new FakeUserManager();
     _emailSender       = Substitute.For <IEmailSender>();
     _jwtConfiguration  = new JwtConfiguration();
     _clubConfiguration = new ClubConfiguration();
     _handler           = new ForgotPassword.Handler(_userManager, _clubConfiguration, _jwtConfiguration, _emailSender);
 }
Пример #24
0
 public AuthController(
     AuthService authService,
     JwtConfiguration secretKeyProvider
     )
 {
     this.authService       = authService;
     this.secretKeyProvider = secretKeyProvider;
 }
Пример #25
0
 public SignUpIdentityController(JwtConfiguration jwtConfiguration,
                                 ILogger <SignUpIdentityController> logger,
                                 IRegistrationService registrationService)
 {
     _jwtConfiguration    = jwtConfiguration;
     _logger              = logger;
     _registrationService = registrationService;
 }
        private static void ShouldThrowForConfiguration(JwtConfiguration configuration, Type expectedExceptionType)
        {
            var options = Options.Create(configuration);

            Should.Throw(
                () => new JwtFactory(options),
                expectedExceptionType);
        }
Пример #27
0
 public JwtService(
     IOptions <JwtConfiguration> jwtConfigurationOptions,
     IUserRepository userRepository
     )
 {
     _jwtConfiguration = jwtConfigurationOptions.Value;
     _userRepository   = userRepository;
 }
Пример #28
0
 public void Setup()
 {
     _userManager       = new FakeUserManager();
     _emailSender       = Substitute.For <IEmailSender>();
     _jwtConfiguration  = new JwtConfiguration();
     _clubConfiguration = new ClubConfiguration();
     _handler           = new CreateEmailConfirmationToken.Handler(_userManager, _clubConfiguration, _jwtConfiguration, _emailSender);
 }
Пример #29
0
 public JwtService(JwtConfiguration jwtConfiguration,
                   IEncryptionService encryptionService)
 {
     _jwtConfiguration  = jwtConfiguration;
     _encryptionService = encryptionService;
     InitializeRsa();
     InitializeJwtParameters();
 }
Пример #30
0
 public UserController(UserManager <User> userManager,
                       SignInManager <User> signInManager,
                       IOptions <JwtConfiguration> jwtOptions)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _jwtOptions    = jwtOptions.Value;
 }