Esempio n. 1
0
        private async Task <ActionResult> LoginInternalAsync(int?account)
        {
            if (!account.HasValue)
            {
                return(Unauthorized("Invalid login or password"));
            }
            var role = await _roles.GetRoleAsync(account.Value);

            var identity = GetClaimsIdentity(account.Value, role);

            var now      = DateTime.UtcNow;
            var jwtToken = new JwtSecurityToken(
                issuer: _jwt.Issuer,
                audience: _jwt.Audience,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(_jwt.LifeTime),
                signingCredentials: new SigningCredentials(_jwt.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            var response   = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            return(Ok(response));
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(optitons => optitons.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            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
                };
            });

            ServiceCreator serviceCreator = new ServiceCreator(Configuration.GetConnectionString("DefaultConnection"));

            services.AddScoped <ICommentService, CommentService>(conf => serviceCreator.CreateCommentService());
            services.AddScoped <IPostService, PostService>(conf => serviceCreator.CreatePostService());
            services.AddScoped <IUserProfileService, UserProfileService>(conf => serviceCreator.CreateUserProfileService());
            services.AddScoped <IApplicationUserService, ApplicationUserService>(conf => serviceCreator.CreateApplicationUserService());
        }
Esempio n. 3
0
        public static ClaimsPrincipal GetClaimsWithToken(string token)
        {
            if (token == null)
            {
                return(null);
            }

            var param = new TokenValidationParameters()
            {
                ValidateAudience         = false,
                ValidateIssuer           = false,
                ValidateLifetime         = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = JwtOptions.GetSymmetricSecurityKey()
            };

            SecurityToken security;

            ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token, param, out security);

            JwtSecurityToken newJwtToken = security as JwtSecurityToken;

            if (newJwtToken == null || !newJwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new SecurityTokenException("Invalid token");
            }
            return(principal);
        }
Esempio n. 4
0
        public static JwtSecurityToken GenerateToken(IEnumerable <Claim> claims)
        {
            var now = DateTime.Now;
            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: JwtOptions.ISSUER,
                audience: JwtOptions.AUDIENCE,
                notBefore: now,
                claims: claims,
                expires: now.Add(TimeSpan.FromMinutes(JwtOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(JwtOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            return(jwt);
        }
Esempio n. 5
0
        public JwtSecurityToken GenerateToken(User user)
        {
            var key = JwtOptions.GetSymmetricSecurityKey();
            var now = DateTime.Now;
            var jwt = new JwtSecurityToken(
                JwtOptions.Issuer,
                JwtOptions.Audience,
                GetIdentity(user).Claims,
                now,
                now.AddMinutes(JwtOptions.Lifetime),
                new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            return(jwt);
        }
Esempio n. 6
0
 private static TokenValidationParameters ConfigureTokenValidationParameters()
 {
     var jwtOptions = new JwtOptions();
     return new TokenValidationParameters
     {
         ValidateIssuer = true,
         ValidIssuer = jwtOptions.Issuer,
         ValidateAudience = true,
         ValidAudience = jwtOptions.Audience,
         ValidateLifetime = true,
         IssuerSigningKey = jwtOptions.GetSymmetricSecurityKey(),
         ValidateIssuerSigningKey = true,
     };
 }
Esempio n. 7
0
        public string GetAccessToken(User user, IList <string> roles)
        {
            var identity = GetIdentity(user, roles);
            var now      = DateTime.UtcNow;
            var jwt      = new JwtSecurityToken(
                issuer: JwtOptions.ISSUER,
                audience: JwtOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(JwtOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(JwtOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)
                );

            return(new JwtSecurityTokenHandler().WriteToken(jwt));
        }
Esempio n. 8
0
        public static JwtSecurityToken CreateToken(User user)
        {
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };

            return(new JwtSecurityToken(
                       issuer: JwtOptions.ISSUER,
                       audience: JwtOptions.AUDIENCE,
                       claims: claims,
                       notBefore: DateTime.Now,
                       expires: DateTime.Now.Add(TimeSpan.FromMinutes(JwtOptions.LIFETIME)),
                       signingCredentials: new SigningCredentials(JwtOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
        }
Esempio n. 9
0
        private string BuildToken(ClaimsIdentity identity)
        {
            var now = DateTime.UtcNow;
            // creating JWT-token
            var jwt = new JwtSecurityToken(
                issuer: JwtOptions.ISSUER,
                audience: JwtOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(JwtOptions.LIFETIME_MINUTES)),
                signingCredentials: new SigningCredentials(JwtOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
Esempio n. 10
0
        public string GenerateJwt(IEnumerable <Claim> claims = null)
        {
            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: _jwtOptionsMonitor.Issuer,
                //audience: _jwtOptionsMonitor.Audience,
                notBefore: now,
                claims: claims,
                expires: now.Add(TimeSpan.FromMinutes(_jwtOptionsMonitor.Lifetime)),
                signingCredentials: new SigningCredentials(_jwtOptionsMonitor.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
Esempio n. 11
0
        private string BuildToken(AccountModel user)
        {
            var identity = GetClaimsIdentity(user.Id, user.Role);

            var now      = DateTime.UtcNow;
            var jwtToken = new JwtSecurityToken(
                issuer: _jwt.Issuer,
                audience: _jwt.Audience,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(_jwt.LifeTime),
                signingCredentials: new SigningCredentials(_jwt.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return(encodedJwt);
        }
Esempio n. 12
0
        private async Task <string> GetJwtTokenAsync(User user)
        {
            var claims = new List <Claim>
            {
                new(ClaimsIdentity.DefaultNameClaimType, user.Login)
            };

            var now      = DateTime.UtcNow;
            var jwtToken =
                new JwtSecurityToken(JwtOptions.Issuer, JwtOptions.Audience, notBefore: now,
                                     claims: claims,
                                     expires: now.Add(TimeSpan.FromDays(JwtOptions.LifeTime)),
                                     signingCredentials: new SigningCredentials(JwtOptions.GetSymmetricSecurityKey(),
                                                                                SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return(encodedJwt);
        }
Esempio n. 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSingleton <SteamManagerConnector>();
            services.AddSingleton <NintendoManagerConnector>();
            services.AddSingleton <PSStoreManagerConnector>();
            services.AddSingleton <UserService>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = JwtOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = JwtOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = JwtOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });
        }
Esempio n. 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));
            services.AddDbContext <Context>(opt =>
            {
                opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,

                    ValidIssuer = JwtOptions.ISSUER,

                    ValidateAudience = true,

                    ValidAudience = JwtOptions.AUDIENCE,

                    ValidateLifetime = true,


                    IssuerSigningKey = JwtOptions.GetSymmetricSecurityKey(),

                    ValidateIssuerSigningKey = true,
                };
                opt.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    },
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];


                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddSignalR();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Esempio n. 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = CurrentEnvironment.IsDevelopment()
                ? Configuration.GetConnectionString("DefaultConnection")
                : HerokuConfiguration.GetHerokuConnectionString();

            services.AddControllers()
            .AddJsonOptions(options =>
                            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

            var jwtOptions    = new JwtOptions();
            var configSection = Configuration.GetSection("JwtOptions");

            configSection.Bind(jwtOptions);

            services.Configure <JwtOptions>(configSection);

            // Custom BadRequest response on ModelState validation
            services.Configure <ApiBehaviorOptions>(o =>
            {
                o.CustomInvalidModelStateResponse();
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidIssuer      = jwtOptions.Issuer,
                    ValidateAudience = false,
                    //ValidAudience = authOptions.Audience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = jwtOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         { options.UseNpgsql(connectionString); });

            services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddRoles <IdentityRole>()
            .AddRoleManager <RoleManager <IdentityRole> >()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddScoped <IJwtGenerator, JwtGenerator>();

            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddCors();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Identity CQRS API",
                    Description = "A simple Asp.Net Core web API which uses CQRS MediatR pattern to handle requests " +
                                  "and Identity to communicate with database. Used jwt authentication."
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }
        /// <summary>
        /// Registers authentication services.
        /// </summary>
        /// <typeparam name="TSessionData">Session data type.</typeparam>
        /// <param name="services">Service collection.</param>
        /// <returns>Service collection.</returns>
        public static IServiceCollection AddServicesInMemory(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddScoped <IRootService, RootService>();
            services.AddScoped <IAuthService, AuthService>();

            //Add storage in memory.
            services.AddScoped <ISessionStorage, SessionStorageInMemory>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IDiceService, DiceService>();

            //Add admin services.
            services.AddScoped <IAdminAddService, AdminAddService>();
            services.AddScoped <IAdminUpdateService, AdminUpdateService>();
            services.AddScoped <IAdminDeleteService, AdminDeleteService>();

            //Add mapper
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            services.AddSingleton(mappingConfig.CreateMapper());

            services.AddCors();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = JwtOptions.RequireHttps;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = JwtOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = JwtOptions.Audience,

                    ValidateLifetime = false,

                    IssuerSigningKey         = JwtOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "VirtualSports", Version = "v1"
                });
                var filePath = Path.Combine(AppContext.BaseDirectory, "VirtualSports.Web.xml");
                if (File.Exists(filePath))
                {
                    options.IncludeXmlComments(filePath);
                }
                options.AddSecurityRequirement(
                    new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            },
                        },
                        new string[0]
                    }
                });

                options.AddSecurityDefinition(
                    "Bearer",
                    new OpenApiSecurityScheme
                {
                    Type         = SecuritySchemeType.ApiKey,
                    In           = ParameterLocation.Header,
                    Scheme       = "Bearer",
                    Name         = "Authorization",
                    Description  = "JWT token",
                    BearerFormat = "JWT"
                });
            });

            services
            .AddAuthentication("JwtAuthentication")
            .AddScheme <JwtBearerOptions, AuthenticationHandler>(
                "JwtAuthentication", null);

            return(services);
        }