コード例 #1
0
        public async Task <AuthorizeResponse> Authorize([FromBody] LoginModel.InputModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new StatusCodeException(SituationCenter.Shared.Exceptions.StatusCode.ArgumentsIncorrect);
            }
            var user = await repository.FindUserByEmailAsync(model.Email);

            if (user == null || !await repository.CheckUserPasswordAsync(user, model.Password))
            {
                throw new StatusCodeException(SituationCenter.Shared.Exceptions.StatusCode.AuthorizeError);
            }

            var claims = new Claim[]
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, "user"),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };
            var identity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
            var now      = DateTime.UtcNow;
            var jwt      = new JwtSecurityToken(
                issuer: MockAuthOptions.ISSUER,
                audience: MockAuthOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(MockAuthOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(MockAuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            logger.LogDebug($"Send token for {user.Email}");
            return(AuthorizeResponse.Create(encodedJwt));
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DataBase")));

            services.AddTransient <IRepository, EntityRepository>();
            services.AddTransient <IRoomManager, RoomsManager>();
            services.AddTransient <IRoomSecurityManager, RoomSecurityManager>();


            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength         = 10;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();


            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = MockAuthOptions.ISSUER,

                    ValidateAudience = true,

                    ValidAudience = MockAuthOptions.AUDIENCE,

                    ValidateLifetime = true,

                    IssuerSigningKey = MockAuthOptions.GetSymmetricSecurityKey(),

                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            });

            // Register no-op EmailSender used by account confirmation and password reset during development
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            services.AddSingleton <IEmailSender, EmailSender>();
        }