Exemplo n.º 1
0
        public string Generate(IEnumerable <Claim> claims)
        {
            var credentials = new SigningCredentials(options.GetSecurityKey(), SecurityAlgorithms.HmacSha256);
            var expiry      = DateTime.Now.Add(options.GetExpiry());
            var token       = new JwtSecurityToken(
                options.Issuer,
                options.Issuer,
                claims,
                expires: expiry,
                signingCredentials: credentials
                );

            return(tokenHandler.WriteToken(token));
        }
Exemplo n.º 2
0
        public async Task<IActionResult> Login([FromBody] LoginRequest model)
        {
            User user = await userManager.FindByNameAsync(model.UserName);
            if (user != null)
            {
                if (await userManager.CheckPasswordAsync(user, model.Password))
                {
                    DateTime now = DateTime.Now;
                    if (user.LastSignedAt == null || user.LastSignedAt < now)
                    {
                        user.LastSignedAt = now;
                        await userManager.UpdateAsync(user);
                    }

                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(ClaimTypes.NameIdentifier, user.Id)
                    };

                    var credentials = new SigningCredentials(configuration.GetSecurityKey(), SecurityAlgorithms.HmacSha256);
                    var expiry = DateTime.Now.Add(configuration.GetExpiry());

                    var token = new JwtSecurityToken(
                        configuration.Issuer,
                        configuration.Issuer,
                        claims,
                        expires: expiry,
                        signingCredentials: credentials
                    );

                    var response = new LoginResponse()
                    {
                        Token = tokenHandler.WriteToken(token)
                    };

                    return Content(json.Serialize(response), "text/json");
                }
            }

            return BadRequest();
        }
Exemplo n.º 3
0
        private IActionResult CreateJwtToken(User user, bool isReadOnly = false)
        {
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            claims.IsReadOnly(isReadOnly);

            var credentials = new SigningCredentials(jwtOptions.GetSecurityKey(), SecurityAlgorithms.HmacSha256);
            var expiry      = DateTime.Now.Add(jwtOptions.GetExpiry());

            var token = new JwtSecurityToken(
                jwtOptions.Issuer,
                jwtOptions.Issuer,
                claims,
                expires: expiry,
                signingCredentials: credentials
                );

            return(Ok(new LoginResponse(tokenHandler.WriteToken(token))));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Login([FromBody] LoginRequest model)
        {
            ApplicationUser user = await userManager.FindByNameAsync(model.UserName);

            if (user != null)
            {
                if (await userManager.CheckPasswordAsync(user, model.Password))
                {
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(ClaimTypes.NameIdentifier, user.Id)
                    };

                    var credentials = new SigningCredentials(configuration.GetSecurityKey(), SecurityAlgorithms.HmacSha256);
                    var expiry      = DateTime.Now.Add(configuration.GetExpiry());

                    var token = new JwtSecurityToken(
                        configuration.Issuer,
                        configuration.Issuer,
                        claims,
                        expires: expiry,
                        signingCredentials: credentials
                        );

                    var response = new LoginResponse()
                    {
                        Token = tokenHandler.WriteToken(token)
                    };

                    return(Ok(response));
                }
            }

            return(BadRequest());
        }
Exemplo n.º 5
0
        public void ConfigureServices(IServiceCollection services)
        {
            ConnectionStrings connectionStrings = Configuration
                                                  .GetSection("ConnectionStrings")
                                                  .Get <ConnectionStrings>();

            string ApplyBasePath(string value) => value.Replace("{BasePath}", Environment.ContentRootPath);

            connectionStrings.Application   = ApplyBasePath(connectionStrings.Application);
            connectionStrings.EventSourcing = ApplyBasePath(connectionStrings.EventSourcing);
            connectionStrings.ReadModel     = ApplyBasePath(connectionStrings.ReadModel);

            services
            .AddDbContext <ApplicationDbContext>(options => options.UseSqlite(connectionStrings.Application));

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                JwtOptions configuration = Configuration.GetSection("Jwt").Get <JwtOptions>();

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = configuration.Issuer,
                    ValidAudience    = configuration.Issuer,
                    IssuerSigningKey = configuration.GetSecurityKey()
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var path = context.HttpContext.Request.Path;
                        if (path.StartsWithSegments("/api"))
                        {
                            var accessToken = context.HttpContext.Request.Query["access_token"];
                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                context.Token = accessToken;
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };

                options.SaveToken = true;
            });

            services
            .AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            services
            .AddIdentityCore <ApplicationUser>(options => Configuration.GetSection("Identity").GetSection("Password").Bind(options.Password))
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services
            .AddRouting(options => options.LowercaseUrls = true)
            .AddControllers()
            .AddNewtonsoftJson();

            services
            .AddSignalR();

            services
            .AddHealthChecks()
            .AddDbContextCheck <ApplicationDbContext>()
            .AddFactoryDbContextCheck <ReadModelContext>()
            .AddFactoryDbContextCheck <EventSourcingContext>();

            services
            .AddTransient <JwtSecurityTokenHandler>()
            .Configure <JwtOptions>(Configuration.GetSection("Jwt"));

            services
            .AddSingleton <Json>()
            .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddSingleton <IUserIdProvider>(new DefaultUserIdProvider())
            .AddTransient <ExceptionMiddleware>()
            .AddSingleton <ApiHub>()
            .AddSingleton <CommandMapper>()
            .AddSingleton <QueryMapper>();

            Bootstrap.BootstrapTask bootstrapTask = new Bootstrap.BootstrapTask(services, connectionStrings);
            bootstrapTask.Initialize();
        }
Exemplo n.º 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            IConfiguration connectionStrings = Configuration.GetSection("Database");

            services
            .AddDbContextWithSchema <AccountContext>(connectionStrings.GetSection("Application"), ApplyBasePath);

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                JwtOptions configuration = Configuration.GetSection("Jwt").Get <JwtOptions>();

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = configuration.Issuer,
                    ValidAudience    = configuration.Issuer,
                    IssuerSigningKey = configuration.GetSecurityKey()
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var path = context.HttpContext.Request.Path;
                        if (path.StartsWithSegments("/api"))
                        {
                            string accessToken = context.HttpContext.Request.Query["access_token"].FirstOrDefault();
                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                context.Token = accessToken;
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };

                options.SaveToken = true;
            });

            services
            .AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            services
            .AddIdentityCore <User>(options => Configuration.GetSection("Identity").GetSection("Password").Bind(options.Password))
            .AddEntityFrameworkStores <AccountContext>();

            services
            .AddRouting(options => options.LowercaseUrls = true)
            .AddControllers()
            .AddNewtonsoftJson();

            services
            .AddVersionHeader();

            services
            .AddSignalR();

            services
            .AddHealthChecks()
            .AddDbContextCheck <AccountContext>()
            .AddFactoryDbContextCheck <ReadModelContext>()
            .AddFactoryDbContextCheck <EventSourcingContext>();

            services
            .AddTransient <JwtTokenGenerator>()
            .AddTransient <JwtSecurityTokenHandler>()
            .Configure <JwtOptions>(Configuration.GetSection("Jwt"));

            services
            .AddSingleton <Json>()
            .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddSingleton <IUserIdProvider>(new DefaultUserIdProvider())
            .AddTransient <ExceptionMiddleware>()
            .AddTransient <RenewableTokenMiddleware>()
            .AddSingleton <ApiHub>()
            .AddSingleton <CommandMapper>()
            .AddSingleton <QueryMapper>();

            var allowedUserPropertyKeys = Configuration.GetSection("UserProperties").Get <string[]>() ?? new string[0];

            Bootstrap.BootstrapTask bootstrapTask = new Bootstrap.BootstrapTask(services, connectionStrings, allowedUserPropertyKeys, ApplyBasePath);
            bootstrapTask.Initialize();
        }