示例#1
0
        private IActionResult Authenticate(string login, string password)
        {
            User user   = authService.Login(login, password);
            var  claims = new List <Claim> {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, user.UserRole.ToString())
            };
            var identity = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
            var jwt      = new JwtSecurityToken(
                issuer: JWTOoptions.Issuer,
                audience: JWTOoptions.Audience,
                notBefore: DateTime.UtcNow,
                claims: identity.Claims,
                expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(JWTOoptions.Lifetime)),
                signingCredentials: new SigningCredentials(JWTOoptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            return(new JsonResult(new {
                access_token = new JwtSecurityTokenHandler().WriteToken(jwt),
                username = identity.Name
            }));
        }
示例#2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DbContext, CreativeCrisisDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            /*services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => //CookieAuthenticationOptions
             *  {
             *      options.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Login");
             *  });*/
            JWTAuthOptions jwtOptions = new JWTAuthOptions();

            Configuration.GetSection("JWTTokenOptions").Bind(jwtOptions);
            services.Configure <JWTAuthOptions>(Configuration.GetSection("JWTTokenOptions"));
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = jwtOptions.Issuer,
                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = jwtOptions.Audience,
                    // будет ли валидироваться время существования
                    ValidateLifetime = true,
                    // установка ключа безопасности
                    IssuerSigningKey = jwtOptions.GetSymmetricSecurityKey(),
                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true,
                };
            });
            services.AddUnitOfWorkAndRepository();
            services.AddBusinessLogicLayer();
            services.AddCors(
                options => options.AddPolicy("AllowAllCors", builder => {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            })
                );
            services.AddMvc();

            // Swagger
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Documentation for API Creative Crisis",
                    Description = "All requirements see here:"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath, true);
                c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description =
                        "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
                    Name   = "Authorization",
                    In     = ParameterLocation.Header,
                    Type   = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });
            });
        }