示例#1
0
        public async Task <IActionResult> Login(LoginRequest request, CancellationToken cancellationToken)
        {
            var validator = new LoginRequestValidator();
            await validator.ValidateAndThrowAsync(request, null, cancellationToken);

            var _privateKey = _configuration.GetSection("AppSettings:PrivateKey").Value;

            if (String.IsNullOrEmpty(_privateKey))
            {
                throw new ControllerException(ErrorCodes.PrivateKeyNotFound, "Controller couldn't retrieve private key");
            }
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);

                if (result.Succeeded)
                {
                    var key       = TokenHelper.BuildRsaSigningKey(_privateKey);
                    var userRoles = await _userManager.GetRolesAsync(user);

                    var token      = TokenHelper.GenerateToken(user.Id, userRoles, key, _dateTimeProvider);
                    var loggedUser = _mapper.Map <LoginResponse>(user);
                    loggedUser.Token = token;

                    return(Ok(loggedUser));
                }
            }

            return(Unauthorized());
        }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.RegisterAssemblyPublicNonGenericClasses(typeof(RepairService).Assembly).Where(x => x.Name.EndsWith("Service")).AsPublicImplementedInterfaces();
            services.RegisterAssemblyPublicNonGenericClasses(typeof(RepairRepository).Assembly).Where(x => x.Name.EndsWith("Repository")).AsPublicImplementedInterfaces();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            var mappingConfiguration = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new Configuration());
            });

            IMapper mapper = mappingConfiguration.CreateMapper();

            services.AddSingleton(mapper);
            services.AddHttpContextAccessor();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IDateTimeProvider, DateTimeProvider>();
            services.AddScoped <IUserContextProvider, UserContextProvider>();
            services.Configure <DataProtectionTokenProviderOptions>(o => o.TokenLifespan = TimeSpan.FromHours(3));

            services.AddControllers().AddNewtonsoftJson();

            IdentityBuilder builder = services.AddIdentityCore <User>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireDigit           = false;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequiredLength         = 3;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <ApplicationDbContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
                options =>
            {
                var publicAuthorizationKey = Configuration.GetSection("AppSettings:PublicKey").Value;
                var key = TokenHelper.BuildRsaSigningKey(publicAuthorizationKey);
                options.TokenValidationParameters = TokenHelper.GetTokenValidationParameters(key);
            })
            .AddCookie(IdentityConstants.ApplicationScheme, options =>
            {
                options.SlidingExpiration = true;
            })
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddExternalCookie();

            services.AddAuthorization(options =>
            {
            });

            services.AddMvc();
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1",
                                   new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title       = "Swagger",
                    Description = "Swagger for my program",
                    Version     = "v1"
                });

                var fileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var filePath = Path.Combine(AppContext.BaseDirectory, fileName);
                options.IncludeXmlComments(filePath);

                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

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