예제 #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(x =>
            {
                x.OutputFormatters.Remove(new XmlDataContractSerializerOutputFormatter());
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver           = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.DateFormatHandling         = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.DateTimeZoneHandling       = DateTimeZoneHandling.Utc;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            services.AddCors();

            var apiJwtToken = new ApiJwtToken();

            Configuration.GetSection(nameof(ApiJwtToken)).Bind(apiJwtToken);

            services.AddSingleton(apiJwtToken);

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.TokenValidationParameters = apiJwtToken.TokenValidationParameters;
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Auth",
                               policy =>
                {
                    policy.RequireAuthenticatedUser().Build();
                });

                auth.AddPolicy("Admin",
                               policy =>
                {
                    policy.RequireAuthenticatedUser().RequireClaim("profile", "Admin").Build();
                });
            });
        }
        public IActionResult Post([FromForm] string userName, [FromForm] string password,
                                  [FromServices] ApiJwtToken apiJwtToken)
        {
            var validUser = ValidUsers.FirstOrDefault(x => x.EmailAddress.Equals(userName) && x.Password.Equals(password));

            if (validUser == null)
            {
                return(BadRequest("User name or password invalid"));
            }

            var claims = new List <Claim>
            {
                new Claim("emailAddress", validUser.EmailAddress),
                new Claim("name", validUser.Name),
                new Claim("profile", validUser.Profile)
            };

            var token = apiJwtToken.GenerateJwtToken(claims);

            return(Ok(new { user = validUser, token }));
        }