Beispiel #1
0
        public AuthenticationControllerTests()
        {
            //setup test database
            settings = new AccountDatabaseSettings()
            {
                AccountsCollectionName       = "accountsCollection",
                AuthenticationCollectionName = "authenticationsCollection",
                ConnectionString             = "ChangeToMongoDBConnectionString",
                DatabaseName = "TestAccountDatabase"
            };
            JwtTokenConfig jwtTokenConfig = new JwtTokenConfig()
            {
                Secret   = "SecretTestingKeyNotForProductionPurposes",
                Issuer   = "AccountService",
                Audience = "",
                AccessTokenExpiration  = 30,
                RefreshTokenExpiration = 30
            };

            AuthenticationManager manager = new AuthenticationManager(settings, jwtTokenConfig);

            controller = new AuthenticationController(manager);

            //mock http requests
            idString = "e70f904b69e7372796e4f799";
            var claim       = new Claim("accountID", idString);
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(m => m.User.IsInRole("admin")).Returns(true);
            httpContext.Setup(m => m.User.FindFirst(ClaimTypes.NameIdentifier)).Returns(claim);

            var controllerContext = new ControllerContext(new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor()));

            controller.ControllerContext = controllerContext;
        }
Beispiel #2
0
 public JwtManager(IOptions <JwtTokenConfig> options, ILogger <JwtManager> logger)
 {
     _options            = options.Value;
     _securityKey        = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecurityKey));
     _signingCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256);
     _logger             = logger;
 }
Beispiel #3
0
        public async Task <Response <string> > Login(string username, string password)
        {
            var response = new Response <string>();

            try
            {
                var user = await _ctx.Users.FirstOrDefaultAsync(c => c.Username.ToLower() == username.ToLower());

                if (user == null)
                {
                    response.Message = "User not found.";
                    response.Success = false;
                    return(response);
                }
                var passwordCheck = VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt);
                if (!passwordCheck)
                {
                    response.Success = false;
                    response.Message = "Invalid username or password";
                    return(response);
                }
                response.Data    = JwtTokenConfig.GetToken(user, _config);
                response.Message = "Logged in successfully";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                return(response);
            }
            return(response);
        }
Beispiel #4
0
        public static IServiceCollection AddJwtTokenService(
            this IServiceCollection services,
            IConfiguration configuration
            )
        {
            var config = new JwtTokenConfig();

            configuration.Bind("JwtToken", config);

            services.AddTransient <IJwtTokenService>(_ => new JwtTokenService(config));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var key = Encoding.UTF8.GetBytes(config.Secret);
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key)
                };
            });

            return(services);
        }
Beispiel #5
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.AddCors(options =>
            {
                options.AddPolicy(corsPolicy,
                                  builder => builder.WithOrigins()
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddScoped <IAuthenticationManager, AuthenticationManager>();
            services.AddScoped <IAccountManager, AccountManager>();

            //get jwt configuration from appsettings
            JwtTokenConfig jwtTokenConfig = Configuration.GetSection("JwtTokenConfig").Get <JwtTokenConfig>();

            services.AddSingleton(jwtTokenConfig);

            //setting up the authentication and add parameters to the validation of the token
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtTokenConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
                    ValidAudience            = jwtTokenConfig.Audience,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("user", policy => policy.RequireClaim("rol", "api_access"));
            });

            services.Configure <AccountDatabaseSettings>(
                Configuration.GetSection(nameof(AccountDatabaseSettings)));

            services.AddSingleton <IAccountDatabaseSettings>(sp =>
                                                             sp.GetRequiredService <IOptions <AccountDatabaseSettings> >().Value);

            services.AddSwaggerGen();
        }
Beispiel #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <IctProjectContext>(options =>
                                                      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
#if DEBUG
                                                      .UseLoggerFactory(MyLoggerFactory)
#endif
                                                      );

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores <IctProjectContext>();

            JwtTokenConfig = Configuration.GetSection("JwtConfig").Get <JwtTokenConfig>();

            string secret = JwtTokenConfig.Secret;
            byte[] key    = Encoding.ASCII.GetBytes(secret);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(x =>
            {
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidIssuer      = JwtTokenConfig.Issuer,
                    ValidAudience    = JwtTokenConfig.Audience
                };
            });

            services.AddControllers();
            services.AddHostedService <JwtRefreshTokenCache>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Web", Version = "v1"
                });

                var securityScheme = new OpenApiSecurityScheme
                {
                    Name         = "JWT Authentication",
                    Description  = "Enter JWT Bearer token **_only_**",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.Http,
                    Scheme       = "bearer",               // must be lower case
                    BearerFormat = "JWT",
                    Reference    = new OpenApiReference
                    {
                        Id   = JwtBearerDefaults.AuthenticationScheme,
                        Type = ReferenceType.SecurityScheme
                    }
                };
                c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { securityScheme, new string[] { } }
                });
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // context
            services.AddDbContext <LocalDbContext>(options =>
                                                   options.UseSqlServer(Configuration.GetConnectionString("Default")));

            services.AddControllers().AddNewtonsoftJson(
                x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );

            services.AddAutoMapper(typeof(AutoMapping));

            // repository
            services.AddScoped <IBidListRepository, BidListRepository>();
            services.AddScoped <ICurvePointRepository, CurvePointRepository>();
            services.AddScoped <IRatingRepository, RatingRepository>();
            services.AddScoped <IRuleRepository, RuleRepository>();
            services.AddScoped <ITradeRepository, TradeRepository>();
            services.AddScoped <IUserRepository, UserRepository>();

            // services
            services.AddTransient <IBidListService, BidListService>();
            services.AddTransient <ICurvePointService, CurvePointService>();
            services.AddTransient <IRatingService, RatingService>();
            services.AddTransient <IRuleService, RuleService>();
            services.AddTransient <ITradeService, TradeService>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IJWTTokenRepository, JWTTokenRepository>();


            services.AddAuthorization();
            services.AddAuthentication(opts =>
            {
                opts.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = JwtTokenConfig.ValidIssuer,
                    ValidAudience    = JwtTokenConfig.ValidAudience,
                    IssuerSigningKey = JwtTokenConfig.GenerateKey(),
                    ClockSkew        = JwtTokenConfig.SkewTime,

                    // security switches
                    RequireExpirationTime    = true,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true
                };
            });

            // Swagger doc
            services.AddSwaggerGen();
        }
 public UsersController(
     IUserService userService,
     IMapper mapper,
     JwtTokenConfig jwtTokenConfig)
 {
     this.userService    = userService;
     this.mapper         = mapper;
     this.jwtTokenConfig = jwtTokenConfig;
 }
 public AuthorizationCommandHandler(IUnitOfWork uow, IDomainNotification notifications,
                                    JwtTokenConfig jwtTokenConfig, IUserRepository userRepository, IPasswordHasherService passwordHasherService,
                                    IShopperRepository shopperRepository) : base(uow, notifications)
 {
     _jwtTokenConfig        = jwtTokenConfig;
     _userRepository        = userRepository;
     _passwordHasherService = passwordHasherService;
     _shopperRepository     = shopperRepository;
 }
 public dynamic Login([FromBody] Authencation obj)
 {
     if (userService.Authencation(obj, _context))
     {
         var tokenString = JwtTokenConfig.BuildToken(_config, obj.UserName);
         return(Ok(new { token = tokenString }));
     }
     return(Unauthorized());
 }
Beispiel #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userToLoginDto"></param>
        /// <returns></returns>
        public async Task <string> LoginUser(UserToLoginDto userToLoginDto)
        {
            var user = await GetUserByEmail(userToLoginDto.Email);

            var roles = await GetUserRoles(user);

            await _signManager.SignInAsync(user, false);

            return(JwtTokenConfig.GetToken(user, _config, roles));
        }
Beispiel #12
0
        public static void AddJwtAuthentication(this IServiceCollection services, JwtTokenConfig jwtTokenConfig)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "DiaryApp", Version = "v1"
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.Http,
                    Scheme      = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtTokenConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
                    ValidAudience            = jwtTokenConfig.Audience,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });
        }
        // 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, IConfiguration configuration)
        {
            _configuration = configuration;
            DependencyInjectionConfig.AddScope(services);

            JwtTokenConfig.AddAuthentication(services, configuration);

            DBContextConfig.Initialize(services, configuration);

            services.AddMvc();
        }
Beispiel #14
0
        public async Task <IActionResult> Login([FromBody] LoginDto model)
        {
            try
            {
                // get device ip
                var currentIp = Utility.getMac();
                Console.WriteLine(currentIp);
                //var isSignedIn = _signInManager.IsSignedIn(User);

                var user = _userManager.Users.FirstOrDefault(x => x.Email == model.Email);
                if (user == null)
                {
                    return(BadRequest("User does not exist"));
                }

                var activityResponse = await _logActivityRepository.GetLogActivity(user.Id);

                if (activityResponse == null)
                {
                    return(BadRequest("No registered user"));
                }

                if (activityResponse.DeviceIp == currentIp && activityResponse.IsActive)
                {
                    return(BadRequest("Already Signed In"));
                }

                // if the user has previously logged in on current device but logged out
                if (activityResponse.DeviceIp == currentIp && !activityResponse.IsActive)
                {
                    activityResponse.LoginTime = DateTime.Now;
                    activityResponse.IsActive  = true;

                    await _logActivityRepository.UpdateLogActivity(activityResponse);
                }
                else
                {
                    return(BadRequest("You are already logged in on another device. Do you want to logout?"));
                }
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

                if (result.Succeeded)
                {
                    var getToken = JwtTokenConfig.GetToken(user, _config);
                    return(Ok(new { message = "Logged in successfully", token = getToken }));
                }
                return(Unauthorized("Incorrect username or Password"));
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(BadRequest("An error occured"));
            }
        }
Beispiel #15
0
        public AuthenticationManager(IAccountDatabaseSettings settings, JwtTokenConfig jwtTokenConfig)
        {
            //token configuration
            this.jwtTokenConfig = jwtTokenConfig;
            this.secret         = Encoding.ASCII.GetBytes(jwtTokenConfig.Secret);

            //mongodb configuration
            MongoClient    client   = new MongoClient(settings.ConnectionString);
            IMongoDatabase database = client.GetDatabase(settings.DatabaseName);

            accounts           = database.GetCollection <Account>(settings.AccountsCollectionName);
            accountCredentials = database.GetCollection <Authentication>(settings.AuthenticationCollectionName);
        }
Beispiel #16
0
 public AccountController(
     SignInManager <AppUser> signInManager,
     UserManager <AppUser> userManager,
     JwtTokenConfig jwtTokenConfig,
     IUnitOfWork unitOfWork,
     IMapper mapper)
 {
     _signInManager  = signInManager;
     _userManager    = userManager;
     _jwtTokenConfig = jwtTokenConfig;
     _unitOfWork     = unitOfWork;
     _mapper         = mapper;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Mutation"/> class.
 /// </summary>
 /// <param name="labelRepo">The label repo.</param>
 /// <param name="toDoItemRepo">To do item repo.</param>
 /// <param name="toDoListRepo">To do list repo.</param>
 /// <param name="userRepo">The user repo.</param>
 /// <param name="httpContextAccessor">The HTTP context accessor.</param>
 /// <param name="tokenConfig">The token configuration.</param>
 public Mutation([Service] ILabelRepo labelRepo, [Service] IToDoItemRepo toDoItemRepo, [Service] IToDoListRepo toDoListRepo,
                 [Service] IUserRepo userRepo, IHttpContextAccessor httpContextAccessor, IOptions <JwtTokenConfig> tokenConfig)
 {
     _labelRepo    = labelRepo;
     _toDoItemRepo = toDoItemRepo;
     _toDoListRepo = toDoListRepo;
     _userRepo     = userRepo;
     _tokenConfig  = tokenConfig.Value;
     if (httpContextAccessor.HttpContext.Items["UserId"] != null)
     {
         _userId = int.Parse(httpContextAccessor.HttpContext.Items["UserId"].ToString());
     }
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ParkingContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:ParkingDB"]));
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy(corsPolicy,
                                  builder => builder.WithOrigins()
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            //get jwt configuration from appsettings
            JwtTokenConfig jwtTokenConfig = Configuration.GetSection("JwtTokenConfig").Get <JwtTokenConfig>();

            services.AddSingleton(jwtTokenConfig);

            //setting up the authentication and add parameters to the validation of the token
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = "AccountService",
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
                    ValidAudience            = jwtTokenConfig.Audience,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("user", policy => policy.RequireClaim("rol", "api_access"));
            });

            services.AddScoped <IParkingGarageManager, ParkingGarageManager>();
            services.AddScoped <IParkingSpotManager, ParkingSpotManager>();
            services.AddScoped <IReservationTimeSlotManager, ReservationTimeSlotManager>();

            services.AddSwaggerGen();
        }
Beispiel #19
0
 public Handler(ClemBotContext context,
                ILogger <BotAuthorize> logger,
                IHttpContextAccessor httpContextAccessor,
                IJwtAuthManager jwtAuthManager,
                JwtTokenConfig jwtTokenConfig,
                ApiKey apiKey)
 {
     _context             = context;
     _logger              = logger;
     _httpContextAccessor = httpContextAccessor;
     _jwtAuthManager      = jwtAuthManager;
     _jwtTokenConfig      = jwtTokenConfig;
     _apiKey              = apiKey;
 }
Beispiel #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddXmlDataContractSerializerFormatters()
            .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

            services.AddCors(options =>
            {
                options.AddPolicy(_kzAllowSpecificOrigins, builder =>
                {
                    //builder.WithOrigins("http://localhost:8080", "http://127.0.0.1:8080")
                    //.AllowAnyHeader()
                    //.AllowAnyMethod()
                    //.AllowCredentials()
                    //.WithExposedHeaders("X-Paginaion");

                    //ÔÊÐíËùÓÐÓò
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("X-Paginaion");
                });
            });

            services.Configure <JwtTokenConfig>(Configuration.GetSection("JwtTokenConfig"));
            JwtTokenConfig tokenConfig = Configuration.GetSection("JwtTokenConfig").Get <JwtTokenConfig>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = tokenConfig.Issuer,
                    ValidAudience    = tokenConfig.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenConfig.Secret))
                };
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <ISessionRepository, SessionRepository>();
            services.AddScoped <ILogRepository, LogRepository>();
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddSingleton <ITokenHelper, TokenHelper>();
            services.AddScoped(typeof(DbContext <>));
            services.AddSingleton <IRedisManager, RedisHelper>();
        }
Beispiel #21
0
 public Handler(ClemBotContext context,
                ILogger <Handler> logger,
                IHttpContextAccessor httpContextAccessor,
                IJwtAuthManager jwtAuthManager,
                JwtTokenConfig jwtTokenConfig,
                IDiscordAuthManager discordAuthManager)
 {
     _context             = context;
     _logger              = logger;
     _httpContextAccessor = httpContextAccessor;
     _jwtAuthManager      = jwtAuthManager;
     _jwtTokenConfig      = jwtTokenConfig;
     _discordAuthManager  = discordAuthManager;
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddFluentValidation(
                fv => fv.RegisterValidatorsFromAssemblyContaining <LoginRequestValdator>());
            var jwtConfig  = new JwtTokenConfig();
            var jwtSetting = Configuration.GetSection("jwtTokenConfig");

            jwtSetting.Bind(jwtConfig);
            services.Configure <JwtTokenConfig>(jwtSetting);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Secret)),
                    ValidAudience            = jwtConfig.Audience,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });
            services.AddSingleton <IJwtAuthManager, JwtAuthManager>();
            services.AddScoped <IUserService, UserService>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "AuthenticationAndAutorization", Version = "v1"
                });
            });

            services.Configure <ApiBehaviorOptions>(
                option => option.InvalidModelStateResponseFactory = context =>
            {
                List <string> errors = context.ModelState.Values
                                       .SelectMany(m => m.Errors.Select(e => e.ErrorMessage))
                                       .ToList();
                return(new BadRequestObjectResult(errors));
            }
                );
        }
Beispiel #23
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            DependencyInjectionConfig.ConfigureServices(services);
            JwtTokenConfig.AddAuthentication(services, _appConfiguration);
            DBContextConfig.Initialize(services, _appConfiguration);

            services.AddAutoMapper();
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Hiroshima API", Version = "v1"
                });
            });
            services.AddCors(options =>
            {
                options.AddPolicy(_defaultCorsPolicyName,
                                  builder =>
                {
                    builder.WithOrigins(_appConfiguration["App:CorsOrigins"])
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName));
            });

            // override modelstate
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var error  = context.ModelState.Values.First().Errors.First().ErrorMessage;
                    var result = new
                    {
                        Title   = "Validation errors",
                        Message = error
                    };
                    return(new BadRequestObjectResult(result));
                };
            });
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            DependencyInjectionConfig.AddScope(services);
            JwtTokenConfig.AddAuthentication(services, Configuration);
            DBContextConfig.Initialize(services, Configuration);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //var connection = @"Server=(localdb)\mssqllocaldb;Organigrama.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
            //services.AddDbContext<ApplicationContext>
            //(options => options.UseSqlServer(connection));
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => {
                configuration.RootPath = "ClientApp/dist";
            });
        }
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     DependencyInjectionConfig.AddScope(services);
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     services.Configure <ConfigurationManager>(Configuration.GetSection("ConfigurationManager"));
     JwtTokenConfig.AddAuthentication(services, Configuration);
     services.AddMvc()
     .AddJsonOptions(options =>
     {
         options.SerializerSettings.ContractResolver = new DefaultContractResolver();
         // This prevents the json serializer from parsing dates
         options.SerializerSettings.DateParseHandling = DateParseHandling.None;
         // This changes how the timezone is converted - RoundtripKind keeps the timezone that was provided and doesn't convert it
         options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
     });
 }
Beispiel #26
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvc(opt => opt.Filters.Add(new ErrorHandlingFilter()));
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            JwtTokenConfig.AddAuthentication(services, Configuration);
            services.Configure <ApiBehaviorOptions>(opt =>
            {
                opt.SuppressModelStateInvalidFilter = true;
            });
            string conStr = Configuration.GetConnectionString("TrackingDatabase");

            services.AddDbContext <TrackingContext>(opt => opt.UseSqlServer(conStr));
        }
        public JwtAuthManagerService(IConfigurationManager configurationManager)
        {
            _configurationManager = configurationManager;

            var    hostConfig = _configurationManager.AppSetting.HostConfig[0];
            string hostUrl    = hostConfig.Host.Contains("localhost") ? "localhost" : hostConfig.Host;

            _jwtTokenConfig = new JwtTokenConfig()
            {
                AccessTokenExpiration  = 8,
                RefreshTokenExpiration = 15,
                Secret   = _configurationManager.AppSetting.CommonConfig.ApplicationSecret,
                Audience = hostUrl,
                Issuer   = hostUrl
            };
            _usersRefreshTokens = new ConcurrentDictionary <string, RefreshToken>();
            _secret             = Encoding.ASCII.GetBytes(_jwtTokenConfig.Secret);
        }
Beispiel #28
0
        /// <summary>
        /// Generates the JWT token.
        /// </summary>
        /// <param name="userDto">The user dto.</param>
        /// <param name="jwtTokenConfig">The JWT token configuration.</param>
        /// <returns></returns>
        public static string GenerateJwtToken(UserDto userDto, JwtTokenConfig jwtTokenConfig)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtTokenConfig.Key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(ClaimTypes.Role, "User"),
                new Claim("UserId", Convert.ToString(userDto.UserId)),
                new Claim("UserName", userDto.UserName),
            };

            var token = new JwtSecurityToken(jwtTokenConfig.Issuer,
                                             jwtTokenConfig.Issuer,
                                             claims,
                                             DateTime.Now.AddHours(2),
                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Beispiel #29
0
        public async Task <ISaida> Autenticar(
            [SwaggerParameter("E-mail do usuário.", Required = true)] string email,
            [SwaggerParameter("Senha do usuário.", Required = true)] string senha,
            [FromServices] JwtTokenConfig tokenConfig /*FromServices: resolvidos via mecanismo de injeção de dependências do ASP.NET Core*/)
        {
            var autenticarComando = new AutenticarUsuarioEntrada(email, senha);

            var comandoSaida = await _usuarioServico.Autenticar(autenticarComando);

            if (!comandoSaida.Sucesso)
            {
                return(comandoSaida);
            }

            var usuario = (UsuarioSaida)comandoSaida.Retorno;

            var dataCriacaoToken   = DateTime.Now;
            var dataExpiracaoToken = dataCriacaoToken + TimeSpan.FromSeconds(tokenConfig.ExpiracaoEmSegundos);

            return(CriarResponseTokenJwt(usuario, dataCriacaoToken, dataExpiracaoToken, tokenConfig));
        }
        public virtual void ConfigureAuthService(IServiceCollection services, JwtTokenConfig jwtConfig)
        {
            services.AddSingleton(jwtConfig);
            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(opt =>
            {
                opt.SaveToken = true;
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Secret)),
                    ValidAudience            = jwtConfig.Audience,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/gamehub")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }