Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = AuthorizeOptions.ISSUER,

                    ValidateAudience = true,

                    ValidAudience    = AuthorizeOptions.AUDIENCE,
                    ValidateLifetime = true,

                    IssuerSigningKey         = AuthorizeOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.OperationFilter <MyHeaderFilter>();

                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "Test API",
                    Description = "ASP.NET Core Web API"
                });
            });
            services.AddSwaggerDocumentation();
        }
        public ActionResult Token()
        {
            var username = Request.Headers["username"];
            var password = Request.Headers["password"];

            var identity = GetIdentity(username, password);

            if (identity == null)
            {
                return(NotFound());
            }

            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: AuthorizeOptions.ISSUER,
                audience: AuthorizeOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthorizeOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthorizeOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            Response.ContentType = "application/json";

            return(Ok(encodedJwt));
        }