コード例 #1
1
        public TokenProviderOptions()
        {
            Path = "/api/token";
            Issuer = "ExampleIssuer";
            Audience = "ExampleAudience";
            Expiration = TimeSpan.FromDays(1);
            var secretKey = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            TokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "ExampleIssuer",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };
        }
コード例 #2
0
ファイル: TokenTest.cs プロジェクト: ychebotarev/InColUn_V0_1
        public void TokenExpirationTest()
        {
            byte[] keyForHmacSha256 = new byte[64];

            var randomGen = RandomNumberGenerator.Create();
            randomGen.GetBytes(keyForHmacSha256);

            var securityKey = new SymmetricSecurityKey(keyForHmacSha256);
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            var options = new TokenProviderOptions
            {
                Issuer = "InColUn",
                Audience = "All",
                SigningCredentials = signingCredentials,
                Expiration = TimeSpan.FromMilliseconds(1000)
            };

            var provider = new TokenProvider(options);

            var token = provider.GenerateUserToken(1, "John Dwo");

            var id = provider.ValidateToken(token.access_token);

            Assert.NotNull(id);
            Assert.Equal(1, id.Value);
        }
コード例 #3
0
ファイル: TokenTest.cs プロジェクト: ychebotarev/InColUn_V0_1
        public void TokenPerformanceTest()
        {
            byte[] keyForHmacSha256 = new byte[64];
            var randomGen = RandomNumberGenerator.Create();
            randomGen.GetBytes(keyForHmacSha256);

            var securityKey = new SymmetricSecurityKey(keyForHmacSha256);
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            var options = new TokenProviderOptions
            {
                Issuer = "InColUn",
                Audience = "All",
                SigningCredentials = signingCredentials
            };

            var provider = new TokenProvider(options);

            for (int i = 0; i < 128 * 2; i++)
            {
                var token = provider.GenerateUserToken(1, "John Dwo");
            }

            Stopwatch stopwatch = Stopwatch.StartNew();
            int limit = 128 * 1024;
            for (int i = 0; i < limit; i++)
            {
                var token = provider.GenerateUserToken(i, "John Dwo");
            }
            stopwatch.Stop();

            var output = string.Format("{0} tokens/sec", 1000.0 * limit / stopwatch.Elapsed.TotalMilliseconds);
            Console.WriteLine(output);
        }
コード例 #4
0
ファイル: Startup.cs プロジェクト: sergey-smirnov/JwtAuth
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var audienceConfig = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var options = new TokenProviderOptions
            {
                Audience = "ExampleAudience",
                Issuer = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = options.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = options.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters,

            });

            app.UseMiddleware<CustomTokenProviderMiddleware>(Options.Create(options));

            app.UseMvc();
        }
コード例 #5
0
        /// <summary>
        /// Generates Defauls SigningCredentials
        /// SigningCredentials generated from random key using HmacSha256Signature algorithm
        /// </summary>
        /// <returns>Generated SigningCredentials</returns>
        public static SigningCredentials DefaultSigningCredentials()
        {
            if (TokenProvider._signingCredentials != null) return TokenProvider._signingCredentials;

            lock(TokenProvider.s_lock)
            {
                if (TokenProvider._signingCredentials != null) return TokenProvider._signingCredentials;
                var keyForHmacSha256 = Common.Crypto.GetRandomBytes(64);

                var securityKey = new SymmetricSecurityKey(keyForHmacSha256);
                _signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
                return _signingCredentials;
            }
        }
コード例 #6
0
ファイル: Startup.cs プロジェクト: Royih/BrewMatic.WebApp
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                builder.AddUserSecrets();
            }
            Configuration = builder.Build();
            _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["SecretKey"]));
        }
コード例 #7
0
ファイル: Startup.cs プロジェクト: ychebotarev/InColUn_V0_1
        private void ConfigureToken(IServiceCollection services)
        {
            byte[] keyForHmacSha256 = new byte[64];

            var randomGen = RandomNumberGenerator.Create();
            randomGen.GetBytes(keyForHmacSha256);

            var securityKey = new SymmetricSecurityKey(keyForHmacSha256);
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            var options = new TokenProviderOptions
            {
                Issuer = "InColUn",
                Audience = "All",
                SigningCredentials = signingCredentials,
                Expiration = TimeSpan.FromMilliseconds(1000)
            };

            var tokenProvider = new TokenProvider(options);

            services.AddSingleton(tokenProvider);
        }
コード例 #8
0
        private string GenerateJwtToken(UserTokenVM request)
        {
            var claims = new List <Claim>
            {
                new Claim("userId", request.UserId.ToString()),
                new Claim("roleId", request.RoleId.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, request.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Auth:JWToken:key"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddSeconds(double.Parse(_configuration["Auth:JWToken:expireValueSeconds"]));

            var token = new JwtSecurityToken(
                _configuration["Auth:JWToken:issuer"],
                _configuration["Auth:JWToken:issuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #9
0
        private string GenerateJwtToken(UserInfo user)
        {
            //create claims details based on the user information
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
                new Claim("Id", user.UserId.ToString()),
                new Claim("FirstName", user.FirstName),
                new Claim("LastName", user.LastName),
                new Claim("UserName", user.UserName),
                new Claim("Email", user.Email)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

            var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

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

            return(jwtToken);
        }
コード例 #10
0
        private SessionToken BuildToken(Aluno aluno)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, aluno.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            // tempo de expiração do token: 1 hora
            var expiration         = DateTime.UtcNow.AddHours(1);
            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(new SessionToken
            {
                Id_User = aluno.Id,
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
コード例 #11
0
        public string GetToken(User user, bool hasCompany)
        {
            var securityKey    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret));
            var credentials    = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var expirationTime = DateTime.UtcNow.AddMinutes(_jwtLifespan);

            var claims = new List <Claim>
            {
                new Claim("Id", Convert.ToString(user.Id)),
                new Claim("Name", Convert.ToString(user.Name)),
                new Claim("Email", Convert.ToString(user.Email)),
                new Claim("hasCompany", Convert.ToString(hasCompany))
            };

            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Site"],
                audience: _configuration["Jwt:Site"],
                expires: expirationTime,
                signingCredentials: credentials,
                claims: claims
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #12
0
ファイル: AuthApi.cs プロジェクト: leandro-cervelin/Todos
        public async Task GenerateTokenAsync(UserManager <TodoUser> userManager, HttpContext context)
        {
            var loginInfo = await JsonSerializer.DeserializeAsync <LoginInfo>(context.Request.Body, _options);

            var user = await userManager.FindByNameAsync(loginInfo?.UserName);

            if (user == null || !await userManager.CheckPasswordAsync(user, loginInfo.Password))
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return;
            }

            var claims = new List <Claim>();

            if (user.IsAdmin)
            {
                claims.Add(new Claim("can_delete", "true"));
                claims.Add(new Claim("can_view", "true"));
            }

            var key   = new SymmetricSecurityKey(_jwtSettings.Key);
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds
                );

            context.Response.ContentType = "application/json";
            await JsonSerializer.SerializeAsync(context.Response.Body, new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
コード例 #13
0
        private string GenerateJSONWebToken(Usuario userInfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.NameId, userInfo.Nome),
                new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, userInfo.IdAcessoNavigation.Tipo)
            };


            var token = new JwtSecurityToken
                        (
                _config["Jwt:Issuer"],
                _config["Jwt:Issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials
                        );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #14
0
        public JwtDto GenerateToken <T>(T model) where T : class, new()
        {
            var jwtToken = GetJwtModel();

            var  secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtToken.JwtKey));
            Type t         = model.GetType();
            var  claims    = new List <Claim>();

            foreach (var property in t.GetProperties())
            {
                claims.Add(new Claim(property.Name, (string)t.GetProperty(property.Name).GetValue(model) ?? ""));
            }

            claims.Add(new Claim(JwtRegisteredClaimNames.Acr,
                                 new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf,
                                 new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Exp,
                                 new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()));

            var token = new JwtSecurityToken(
                issuer: jwtToken.JwtIssuer,
                audience: jwtToken.JwtAudience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(jwtToken.JwtExpireDays),
                signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256)
                );

            return(new JwtDto()
            {
                Type = JwtBearerDefaults.AuthenticationScheme,
                AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
                Expires = DateTime.Now.AddDays(jwtToken.JwtExpireDays)
            });
        }
コード例 #15
0
ファイル: JwtGenerator.cs プロジェクト: neilxc/activityhub
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.NameId, user.UserName)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["AppSettings:Token"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
コード例 #16
0
        private void ConfigureJwtAuthenticationService(IConfiguration configuration, IServiceCollection services)
        {
            var audience     = Configuration.GetSection("Audience");
            var symmetrickey = audience["secret"];
            var byteArray    = Encoding.ASCII.GetBytes(symmetrickey);
            var signingkey   = new SymmetricSecurityKey(byteArray);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingkey,
                ValidateIssuer           = true,
                ValidIssuer      = audience["issuer"],
                ValidateAudience = true,
                ValidAudience    = audience["audience"],
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.FromMinutes(5)
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o => o.TokenValidationParameters = tokenValidationParameters);
        }
コード例 #17
0
        public IActionResult GenerateToken([FromQuery] string username, [FromQuery] string password)
        {
            bool isValidUser = _authService.IsValid(username, password);
            if (!isValidUser)
            {
                return BadRequest("invalid user/pass combination");
            }

            var claims = _authService.GetUserClaims(username).Select(name => new Claim(name, "true"));

            var key = new SymmetricSecurityKey(JwtSettings.Instance.Key);
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: JwtSettings.Instance.Issuer,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds
                );

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
コード例 #18
0
        private string GenerateJSONWebToken(UserModel user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Email, user.EmailAddress),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, user.Role)
            };

            var token = new JwtSecurityToken(
                issuer: _config["Jwt:Issuer"],
                audience: _config["Jwt:Issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(20),
                signingCredentials: credentials);

            var encodeToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(encodeToken);
        }
コード例 #19
0
ファイル: TokenController.cs プロジェクト: sw0/netcoresamples
        public IActionResult Generate()
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, "some_identity_id"),
                new Claim("teacher says", "he is good boy")
            };

            var secret = Encoding.UTF8.GetBytes(AppConsts.Secret);
            var key    = new SymmetricSecurityKey(secret);

            var algorithm = SecurityAlgorithms.HmacSha256;

            var signingCredentials = new SigningCredentials(key, algorithm);

            var jwt = new JwtSecurityToken(AppConsts.Issuer, AppConsts.Audience, claims,
                                           notBefore: DateTime.Now,
                                           expires: DateTime.Now.AddHours(12),
                                           signingCredentials);

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

            return(Ok(new { access_token = tokenString }));
        }
コード例 #20
0
ファイル: AccountController.cs プロジェクト: radtek/Rowcall
        // Generates a Json Web Token and returns it to the user. The user should store and use this in every request
        // For every authorized request use following header: "authorization" and set value to "Bearer your-token-here"
        private async Task <string> GenerateJwtToken(string email, IdentityUser user, string roleName)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Role, roleName)
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));

            var token = new JwtSecurityToken(
                _configuration["JwtIssuer"],
                _configuration["JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #21
0
        public async Task <IActionResult> Post(Customer customer)
        {
            if (customer != null && customer.Email != null && customer.Password != null)
            {
                var user = await GetUser(customer.Email, customer.Password);

                if (user != null)
                {
                    //create claims details based on the user information
                    var claims = new[] {
                        new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
                        new Claim("Id", user.CustomerId.ToString()),
                        new Claim("Name", user.Name),
                        new Claim("Email", user.Email)
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

                    var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                    return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
                }
                else
                {
                    return(BadRequest("Invalid credentials"));
                }
            }
            else
            {
                return(BadRequest());
            }
        }
コード例 #22
0
        public string CreateToken(User user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.NameId, user.Email)
            };

            // generate signing credentials
            var key             = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super secret key"));
            var creds           = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);


            return(tokenHandler.WriteToken(token));
        }
コード例 #23
0
        public static string GenerateToken(string randomString, string secretKey, string issuer, string audience)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, randomString),
                    new Claim(MemberPropertyEnum.MemberEmail.ToString(), "*****@*****.**"),
                }),
                Expires            = DateTime.Now.AddDays(7),
                Issuer             = issuer,
                Audience           = audience,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };

            JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);

            token.Payload["favouriteFood"] = "cheese";

            return(handler.WriteToken(token));
        }
コード例 #24
0
        private string CreateJWT(User user)
        {
            var secretKey = configuration.GetSection("AppSettings:Key").Value;
            var key       = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var claims    = new Claim[] {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };
            var signingCredentials = new SigningCredentials(
                key, SecurityAlgorithms.HmacSha256Signature
                );

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(10),
                SigningCredentials = signingCredentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
コード例 #25
0
        public IActionResult GetToken()
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, "Steve"),
                new Claim(ClaimTypes.Email, Constants.UserEmail)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSigningKey"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "yourdomain.com",
                audience: "yourdomain.com",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
コード例 #26
0
        private async Task <string> GenerateJwtTokenAsync(string userName)
        {
            var user = await _userManager.FindByEmailAsync(userName);

            var roles = await _userManager.GetRolesAsync(user);

            // just for the first time
            if (user.Email == "*****@*****.**")
            {
                user.IsAdmin = true;
                await _dbContext.SaveChangesAsync();
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim("UserId", user.Id.ToString()),
                (user.IsAdmin)
                    ?new Claim(ClaimTypes.Role, "admin")
                    :new Claim(ClaimTypes.Role, "member")
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("M!nAAzManBehtanNist!!!!ValiManKharamUnKharTa@re"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "M!nA",
                audience: "M!nA",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            var stringToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(stringToken);
        }
コード例 #27
0
        public object GetJwtToken()
        {
            var userId = User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;

            string key      = _configuration.GetValue <string>("Jwt:EncryptionKey");
            string issuer   = _configuration.GetValue <string>("Jwt:Issuer");
            string audience = _configuration.GetValue <string>("Jwt:Audience");

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var permClaims = new List <Claim>();

            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("discordId", userId));

            var token    = new JwtSecurityToken(issuer, audience, permClaims, null, DateTime.Now.AddDays(30), credentials);
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(new
            {
                ApiToken = jwtToken
            });
        }
コード例 #28
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username, userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.
                                               GetBytes(_Config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDiscriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDiscriptor);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token)
            }));
        }
コード例 #29
0
        private string GenerateTokenbk()
        {
            //Header

            SymmetricSecurityKey _symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecrectKey"]));
            SigningCredentials   signingCredentials    = new SigningCredentials(_symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
            JwtHeader            header = new JwtHeader(signingCredentials);

            //Claims
            Claim[] claims = new[]
            {
                new Claim(ClaimTypes.Name, "Franklin Reveron"),

                new Claim(ClaimTypes.Role, "Admin"),

                new Claim(ClaimTypes.Email, "*****@*****.**"),
            };


            //Payload

            JwtPayload payload = new JwtPayload
                                 (

                _configuration["Authentication:Issuer"],
                _configuration["Authentication:Audience"],
                claims,
                DateTime.Now,
                DateTime.UtcNow.AddMinutes(20)

                                 );

            var token = new JwtSecurityToken(header, payload);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #30
0
ファイル: Startup.cs プロジェクト: alperkavusturan/SE
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var audConfig  = Configuration.GetSection("Audience");
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audConfig["Secret"]));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = audConfig["Iss"],
                ValidateAudience      = true,
                ValidAudience         = audConfig["Aud"],
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
                RequireExpirationTime = true
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "JwtKey";
                options.DefaultChallengeScheme    = "JwtKey";
            }).AddJwtBearer("JwtKey", x =>
            {
                x.RequireHttpsMetadata      = false;
                x.TokenValidationParameters = tokenValidationParameters;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddLogging(loginBuilder =>
            {
                loginBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                loginBuilder.AddConsole();
                loginBuilder.AddDebug();
            });
            services.AddOcelot(Configuration);
        }
コード例 #31
0
        public string GenerateJwtToken([NotNull] UserModel user)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Role, UserRole.User.ToString(), UserRole.Admin.ToString())
            };

            SymmetricSecurityKey key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.JwtKey));
            SigningCredentials   credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            DateTime             expires     = DateTime.Now.AddDays(Convert.ToDouble(_settings.JwtExpireDays));

            JwtSecurityToken token = new JwtSecurityToken(
                _settings.JwtIssuer,
                _settings.JwtIssuer,
                claims,
                expires: expires,
                signingCredentials: credentials
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #32
0
        /// <summary>
        /// JWT erzeugen. Minimale Claim-Infos: Email und Rolle
        /// </summary>
        /// <returns>Token mit Claims</returns>
        private string GenerateJwtToken(string email, IEnumerable <string> roles)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var authClaims = new List <Claim>
            {
                new Claim(ClaimTypes.Email, email)
            };

            foreach (string role in roles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, role));
            }

            var token = new JwtSecurityToken(
                issuer: _config["Jwt:Issuer"],
                audience: _config["Jwt:Audience"],
                claims: authClaims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #33
0
        public object GenerateJwtToken(string email, int id, UserDTO user, IConfiguration _config)
        {
            var claims = new [] {
                new Claim(JwtRegisteredClaimNames.Sub, user.Username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var jwtkey = _config["Jwt:Key"];
            var issuer = _config["Jwt:JwtIssuer"];

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                _config["Jwt:JwtIssuer"],
                _config["Jwt:JwtIssuer"],
                claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);
            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            return(tokenString);
        }
コード例 #34
0
        public IActionResult RefreshToken(RefreshReq refreshReq)
        {
            if (!securityDb.checkIfTokenExists(refreshReq.refreshToken))
            {
                return(NotFound());
            }


            var claims = new[]
            {
                new Claim(ClaimTypes.Role, "Employee"),
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecretKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);

            var token = new JwtSecurityToken
                        (
                issuer: "Program",
                audience: "Ktokolwiek",
                claims: claims,
                expires: DateTime.Now.AddMinutes(60),
                signingCredentials: credentials
                        );

            var rToken = Guid.NewGuid();

            securityDb.createRefreshToken(rToken);


            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = rToken
            }));
        }
コード例 #35
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext> (options => {
                options.UseSqlServer(Configuration.GetConnectionString("ApplicationConnection"));
            });
            services.AddIdentity <IdentityUser, IdentityRole> ().AddEntityFrameworkStores <ApplicationDbContext> ();
            services.AddMvc()
            .AddJsonOptions(opt => {
                opt.SerializerSettings.ReferenceLoopHandling =
                    ReferenceLoopHandling.Ignore;
            });
            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is the secret phrase"));

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg => {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = signingKey,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = false,
                    ValidateIssuerSigningKey = true
                };
            });
            services.AddCors(options => options.AddPolicy("Cors", builder => {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            services.AddScoped <IEmployee, EmployeeRepository> ();
        }
コード例 #36
0
        private async Task <string> GenerateJSONWebToken(IdentityUser user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claims      = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };
            var roles = await _userManager.GetRolesAsync(user);

            claims.AddRange(roles.Select(r => new Claim(ClaimsIdentity.DefaultRoleClaimType, r)));

            var token = new JwtSecurityToken(_config["Jwt:Issuer"]
                                             , _config["Jwt:Issuer"],
                                             claims,
                                             null,
                                             expires: DateTime.Now.AddHours(5),
                                             signingCredentials: credentials
                                             );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #37
0
        private UserToken BuildToken(string email, IList <string> roles)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            foreach (var rol in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, rol));
            }

            DateTime             expiration = DateTime.UtcNow.AddHours(1);
            SymmetricSecurityKey key        = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"]));
            SigningCredentials   creds      = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken     token      = new JwtSecurityToken(claims: claims, expires: expiration, signingCredentials: creds);

            return(new UserToken()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = expiration
            });
        }
コード例 #38
0
ファイル: Startup.cs プロジェクト: ZA-PT/Obsidian
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SagaBus sagaBus,
            IOptions<OAuth20Configuration> oauthOptions)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Obsidian.Cookie",
                AutomaticChallenge = false,
                AutomaticAuthenticate = false
            });

            var oauthConfig = oauthOptions.Value;
            var key = oauthConfig.TokenSigningKey;
            var signingKey = new SymmetricSecurityKey(Encoding.Unicode.GetBytes(key));
            var param = new TokenValidationParameters
            {
                AuthenticationType = "Bearer",
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = oauthConfig.TokenIssuer,
                ValidAudience = oauthConfig.TokenAudience
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                TokenValidationParameters = param,
                AutomaticAuthenticate = false,
                AutomaticChallenge = false
            });

            app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });

            MappingConfig.ConfigureQueryModelMapping();
            sagaBus.RegisterSagas();
        }
コード例 #39
0
ファイル: Startup.cs プロジェクト: AlinCiocan/FoodPlanApp
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Pantry, PantryViewModel>().ReverseMap();
                cfg.CreateMap<PantryItem, PantryItemViewModel>().ReverseMap();
            });

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>();
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            //TODO: Make sure to put this variable in a config & keep it safe
            string SecretKey = Configuration["SecretKey"];
            Console.WriteLine($"Secret key: {SecretKey}");
            _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

            services.Configure<JwtIssuerOptions>(options =>
            {
                options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            // Add application services
            services.AddTransient<PantryService, PantryService>();

            services.Configure<IdentityOptions>(options =>
               {
               // Password settings
               options.Password.RequireDigit = false;
               options.Password.RequiredLength = 6;
               options.Password.RequireNonAlphanumeric = false;
               options.Password.RequireUppercase = false;
               options.Password.RequireLowercase = false;

               // User settings
               options.User.RequireUniqueEmail = true;
               });

            var sqlConnectionString = Configuration["ConnectionStrings:DataAccessMySqlProvider"];
            Console.WriteLine($"sql conn from config file: {sqlConnectionString}");

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySQL(sqlConnectionString)
            );

            string currentDirectory = Directory.GetCurrentDirectory();
            Console.WriteLine($"Current directory: {currentDirectory}");
        }