// The Method is used to generate token for user when user is authentic.
        public string GenerateTokenForUser(string userName, int userId)
        {
            var signingKey         = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(communicationKey));
            var now                = DateTime.UtcNow;
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey,
                                                                                           System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature,
                                                                                           System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest);

            var claimsIdentity = new ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
            }, "Custom");

            var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                //AppliesToAddress = "http://www.example.com",
                //TokenIssuerName = "self",

                Issuer  = "self",
                Expires = DateTime.MaxValue,

                Subject            = claimsIdentity,
                SigningCredentials = signingCredentials,
                //Lifetime = new Lifetime(now, now.AddYears(1)),
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var plainToken            = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
Beispiel #2
0
        public models.SecurityToken Authenticate(string email, string password)
        {
            var user = _users.SingleOrDefault(x => x.Email == email && x.Password == password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("id", user.Id.ToString()),
                    new Claim("firstName", user.FirstName),
                    new Claim("lastName", user.LastName),
                    new Claim("email", user.Email),
                    new Claim("profilePicture", user.ProfilePicture)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
            };
            var token            = tokenHandler.CreateToken(tokenDescriptor);
            var jwtSecurityToken = tokenHandler.WriteToken(token);

            return(new models.SecurityToken()
            {
                Auth_token = jwtSecurityToken
            });
        }
Beispiel #3
0
        public string IssueToken(Microsoft.AspNetCore.Authentication.AuthenticationTicket data)
        {
            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            System.DateTime now = System.DateTime.UtcNow;

            Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor desc =
                new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                //Subject = new System.Security.Claims.ClaimsIdentity(claimList),
                Subject            = (System.Security.Claims.ClaimsIdentity)data.Principal.Identity,
                Issuer             = this.m_validationParameters.ValidIssuer,   //SecurityConstants.TokenIssuer,
                Audience           = this.m_validationParameters.ValidAudience, // SecurityConstants.TokenAudience,
                IssuedAt           = now,
                Expires            = now.AddMinutes(this.m_tokenLifetimeMinutes),
                NotBefore          = now.AddTicks(-1),
                SigningCredentials = this.m_signingCredentials
            };

            // System.IdentityModel.Tokens.Jwt.JwtSecurityToken tok =
            //        tokenHandler.CreateJwtSecurityToken(desc);
            // // tok.Header.Add("jti", "foo");
            // // tok.Payload.Add("jti", "foobar");

            // System.Console.WriteLine(tok.Id);

            // string tokk = tok.ToString();
            // System.Console.WriteLine(tokk);

            return(tokenHandler.CreateEncodedJwt(desc));
        } // End Function IssueToken
Beispiel #4
0
        public string PublishToken(string userName, string password, int epireTime, int notBeforeTime)
        {
            var hmac         = new HMACSHA256();
            var key          = Convert.ToBase64String(hmac.Key);
            var symmetricKey = Convert.FromBase64String(key);

            var tokenHandler = new JwtSecurityTokenHandler();

            var now = DateTime.Now;

            var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Email, userName),
                    new Claim(ClaimTypes.Hash, password),
                }),
                NotBefore          = now.AddMinutes(Convert.ToInt32(notBeforeTime)),
                Expires            = now.AddMinutes(Convert.ToInt32(epireTime)),
                SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(symmetricKey), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
            };

            var stoken = tokenHandler.CreateToken(tokenDescriptor);
            var token  = tokenHandler.WriteToken(stoken);

            return(token);
        }
 public override System.IdentityModel.Tokens.SecurityToken CreateToken(Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor tokenDescriptor)
 {
     Utility.VerifyNonNullArgument("tokenDescriptor", tokenDescriptor);
     if (tokenDescriptor.SigningCredentials == null)
     {
         throw new System.ArgumentException("tokenDescriptor.SigningCredentials cannot be null");
     }
     if (tokenDescriptor.Subject == null)
     {
         throw new System.ArgumentException("tokenDescriptor.Subject cannot be null");
     }
     if (string.IsNullOrEmpty(tokenDescriptor.TokenIssuerName))
     {
         throw new System.ArgumentException("tokenDescriptor.TokenIssuerName cannot be null");
     }
     System.DateTime dateTime = System.DateTime.UtcNow;
     System.DateTime validTo  = DateTimeUtil.Add(dateTime, System.TimeSpan.FromHours(1.0));
     if (tokenDescriptor.Lifetime != null)
     {
         if (tokenDescriptor.Lifetime.Created.HasValue)
         {
             dateTime = DateTimeUtil.ToUniversalTime(tokenDescriptor.Lifetime.Created.Value);
         }
         if (tokenDescriptor.Lifetime.Expires.HasValue)
         {
             validTo = DateTimeUtil.ToUniversalTime(tokenDescriptor.Lifetime.Expires.Value);
         }
     }
     System.Collections.Generic.List <JsonWebTokenClaim> list = new System.Collections.Generic.List <JsonWebTokenClaim>();
     foreach (Claim current in tokenDescriptor.Subject.Claims)
     {
         list.Add(new JsonWebTokenClaim(current.ClaimType, current.Value));
     }
     return(new JsonWebSecurityToken(tokenDescriptor.TokenIssuerName, this.GetAppliesTo(tokenDescriptor), dateTime, validTo, list, tokenDescriptor.SigningCredentials));
 }
Beispiel #6
0
        private string IssueJwtToken(System.IdentityModel.Tokens.Jwt.JwtSecurityToken aadToken)
        {
            var msKey = GetTokenSignKey();

            var msSigningCredentials = new Microsoft.IdentityModel.Tokens
                                       .SigningCredentials(msKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"),
                new Claim(ClaimTypes.Role, "admin"),
            }, "MassRover.Authentication");

            var msSecurityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Audience           = "massrover.client",
                Issuer             = "massrover.authservice",
                Subject            = claimsIdentity,
                Expires            = DateTime.UtcNow.AddHours(8),
                SigningCredentials = msSigningCredentials
            };

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var plainToken = tokenHandler.CreateToken(msSecurityTokenDescriptor);

            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
        public async Task <ApplicationUser> Authenticate(LoginViewModel loginViewModel)
        {
            var result = await _applicationSignInManager.PasswordSignInAsync(loginViewModel.Username, loginViewModel.Password, false, false);

            if (result.Succeeded)
            {
                var applicationUser = await _applicationUserManager.FindByNameAsync(loginViewModel.Username);

                applicationUser.PasswordHash = null;

                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                {
                    Subject = new ClaimsIdentity(new Claim[] {
                        new Claim(ClaimTypes.Name, applicationUser.Id),
                        new Claim(ClaimTypes.Email, applicationUser.Email)
                    }),
                    Expires            = DateTime.UtcNow.AddHours(8),
                    SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                applicationUser.Token = tokenHandler.WriteToken(token);

                return(applicationUser);
            }
            else
            {
                return(null);
            }
        }
Beispiel #8
0
        public static string generateToken(us user, Main setings)
        {
            byte[] key             = Encoding.ASCII.GetBytes(setings.key);
            var    securitykey     = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key: key);
            var    alguritm        = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature;
            var    creatioal       = new Microsoft.IdentityModel.Tokens.SigningCredentials(securitykey, alguritm);
            var    tokendiscriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject = new System.Security.Claims.ClaimsIdentity
                              (new[]
                {
                    new System.Security.Claims.Claim(nameof(user.lastname), user.lastname),
                    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, user.firstname),
                    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, user.email),
                    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, user.id.ToString()),
                }),


                Expires            = DateTime.UtcNow.AddMinutes(setings.timeOut),
                SigningCredentials = creatioal,
            };
            var tokenHandled = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            Microsoft.IdentityModel.Tokens.SecurityToken securitytoken = tokenHandled.CreateToken(tokendiscriptor);
            string token = tokenHandled.WriteToken(securitytoken);

            return(token);
        }
Beispiel #9
0
        public ActionResult <User> Login([FromBody] User user)
        {
            if (user.Name != "Dinesh" || user.Password != "123456")
            {
                return(NotFound());
            }
            else
            {
                var tokenHandler     = new JwtSecurityTokenHandler();
                var key              = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey);
                var tokenDescriptior = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[] {
                        new Claim(ClaimTypes.Name, user.Name)
                    }),
                    Expires            = DateTime.UtcNow.AddMinutes(2),
                    SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                        new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key),
                        Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
                };

                var token = tokenHandler.CreateToken(tokenDescriptior);
                user.Token = tokenHandler.WriteToken(token);
                return(user);
            }
        }
 protected virtual string GetAppliesTo(Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor tokenDescriptor)
 {
     if (string.IsNullOrEmpty(tokenDescriptor.AppliesToAddress))
     {
         throw new System.ArgumentException("tokenDescriptor.AppliesToAddress cannot be null");
     }
     return(tokenDescriptor.AppliesToAddress);
 }
        public async Task <ApplicationUser> Register(RegisterViewModel signUpViewModel)
        {
            var applicationUser = new ApplicationUser();

            applicationUser.UserName  = signUpViewModel.Name;
            applicationUser.Email     = signUpViewModel.Email;
            applicationUser.CountryId = signUpViewModel.CountryId;
            applicationUser.StateId   = signUpViewModel.StateId;
            applicationUser.CityId    = signUpViewModel.CityId;
            applicationUser.Role      = "Employee";

            var result = await userManager.CreateAsync(applicationUser, signUpViewModel.Password);

            if (result.Succeeded)
            {
                if ((await userManager.AddToRoleAsync(await userManager.FindByNameAsync(signUpViewModel.Email), "Employee")).Succeeded)
                {
                    var result2 = await signInManager.PasswordSignInAsync(signUpViewModel.Email, signUpViewModel.Password, false, false);

                    if (result2.Succeeded)
                    {
                        //token
                        var tokenHandler    = new JwtSecurityTokenHandler();
                        var key             = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
                        var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                        {
                            Subject = new ClaimsIdentity(new Claim[] {
                                new Claim(ClaimTypes.Name, applicationUser.Id),
                                new Claim(ClaimTypes.Email, applicationUser.Email),
                                new Claim(ClaimTypes.Role, applicationUser.Role)
                            }),
                            Expires            = DateTime.UtcNow.AddHours(8),
                            SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        applicationUser.Token = tokenHandler.WriteToken(token);

                        return(applicationUser);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Beispiel #12
0
        public static string GenerateJwtToken(Models.User user, string secretKey)
        {
            // Generate token that is valid for 8 hours

            var key =
                System.Text.Encoding.ASCII.GetBytes(secretKey);

            var symmetricSecurityKey =
                new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key: key);

            var securityAlgorithm =
                Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature;

            var signingCredentials =
                new Microsoft.IdentityModel.Tokens
                .SigningCredentials(key: symmetricSecurityKey, algorithm: securityAlgorithm);

            var tokenDescriptor =
                new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject =
                    new System.Security.Claims.ClaimsIdentity
                        (new[]
                {
                    new System.Security.Claims.Claim
                        (type: "LastName", value: user.LastName),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.Name, value: user.Username),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.Email, value: user.EmailAddress),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.NameIdentifier, value: user.Id.ToString()),
                }),

                Expires =
                    System.DateTime.UtcNow.AddHours(8),

                SigningCredentials = signingCredentials,
            };

            var tokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var token =
                tokenHandler.CreateToken(tokenDescriptor: tokenDescriptor);

            string tokenString =
                tokenHandler.WriteToken(token: token);

            return(tokenString);
        }
        public static Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor Convert(SecurityTokenDescriptor tokenDescriptor)
        {
            v1SecurityTokenDescriptor v1TokenDescriptor = new v1SecurityTokenDescriptor();

            if (tokenDescriptor.AppliesToAddress != null)
            {
                v1TokenDescriptor.AppliesToAddress = tokenDescriptor.AppliesToAddress;
            }

            if (tokenDescriptor.AttachedReference != null)
            {
                v1TokenDescriptor.AttachedReference = tokenDescriptor.AttachedReference;
            }

            if (tokenDescriptor.AuthenticationInfo != null)
            {
                v1TokenDescriptor.AuthenticationInfo = Convert(tokenDescriptor.AuthenticationInfo);
            }

            if (tokenDescriptor.Lifetime != null)
            {
                v1TokenDescriptor.Lifetime = new Microsoft.IdentityModel.Protocols.WSTrust.Lifetime(tokenDescriptor.Lifetime.Created, tokenDescriptor.Lifetime.Expires);
            }

            if (tokenDescriptor.ReplyToAddress != null)
            {
                v1TokenDescriptor.ReplyToAddress = tokenDescriptor.ReplyToAddress;
            }

            if (tokenDescriptor.SigningCredentials != null)
            {
                v1TokenDescriptor.SigningCredentials = tokenDescriptor.SigningCredentials;
            }

            if (tokenDescriptor.Subject != null)
            {
                v1TokenDescriptor.Subject = Convert(tokenDescriptor.Subject);
            }

            if (tokenDescriptor.TokenIssuerName != null)
            {
                v1TokenDescriptor.TokenIssuerName = tokenDescriptor.TokenIssuerName;
            }

            if (tokenDescriptor.TokenType != null)
            {
                v1TokenDescriptor.TokenType = tokenDescriptor.TokenType;
            }

            return(v1TokenDescriptor);
        }
Beispiel #14
0
        public async Task <ApplicationUser> Authenticate(LoginViewModel loginViewModel)
        {
            try
            {
                var result = await _applicationSignInManager.PasswordSignInAsync(loginViewModel.UserName, loginViewModel.Password, false, false);

                if (result.Succeeded)
                {
                    var applicationUser = await _applicationUserManager.FindByNameAsync(loginViewModel.UserName);

                    applicationUser.PasswordHash = null;
                    if (await this._applicationUserManager.IsInRoleAsync(applicationUser, "Admin"))
                    {
                        applicationUser.Role = "Admin";
                    }
                    else if (await this._applicationUserManager.IsInRoleAsync(applicationUser, "Employee"))
                    {
                        applicationUser.Role = "Employee";
                    }

                    var tokenHandler    = new JwtSecurityTokenHandler();
                    var key             = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
                    var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                    {
                        //payload
                        Subject = new ClaimsIdentity(new Claim[] {
                            new Claim(ClaimTypes.Name, applicationUser.Id),
                            new Claim(ClaimTypes.Email, applicationUser.Email),
                            new Claim(ClaimTypes.Role, applicationUser.Role)
                        }),
                        //payload
                        Expires = DateTime.UtcNow.AddHours(8),
                        //hashing algorithm
                        SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
                    };
                    var token = tokenHandler.CreateToken(tokenDescriptor);
                    applicationUser.Token = tokenHandler.WriteToken(token);

                    return(applicationUser);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #15
0
        public ApiResponse Login(dynamic loginData)
        {
            string email    = loginData.Email;
            string password = loginData.Password;
            string name     = string.Empty;

            using (var context = new AgmDataContext())
            {
                if (context.Users.All(u => u.Email.ToLower() != email.ToLower() || u.Password != password || u._sectionMonthlyReportsVisible != 1 || u._isDeleted || u._isActive != 1))
                {
                    return new ApiResponse(false)
                           {
                               Errors =
                                   new ApiResponseError[]
                               { new ApiResponseError()
                                 {
                                     Message = "Email o password errati"
                                 } }
                           }
                }
                ;

                name = context.Users.First(u => u.Email.ToLower() == email.ToLower() && u.Password == password && !u._isDeleted).Name;
            }

            var tokenHandler = new JwtSecurityTokenHandler();

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, string.Format("{0}${1}", loginData.Email.ToString(), name))
            };

            var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(claims),
                Issuer  = "Agm"
            };

            var jwtToken = tokenHandler.CreateToken(tokenDescriptor);

            return(new ApiResponse()
            {
                Succeed = true,
                Token = tokenHandler.WriteToken(jwtToken)
            });
        }
Beispiel #16
0
        public bool GenerateDomainToken(DomainUser user)
        {
            log.WriteLogEntry("Starting GenerateDomainToken...");
            bool result = false;

            log.WriteLogEntry(string.Format("Current user {0} {1}", user.DomainUpn, user.UserEmail));
            try
            {
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                byte[] rngKey             = new byte[32];
                rng.GetBytes(rngKey);
                var signatureKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(rngKey);
                log.WriteLogEntry("Success create security key.");
                var signatureCreds = new Microsoft.IdentityModel.Tokens.SigningCredentials(signatureKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                log.WriteLogEntry("Success create signing credentials.");
                var claimsID = new ClaimsIdentity(new List <Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, user.DomainUpn),
                    new Claim(ClaimTypes.Email, user.UserEmail),
                    new Claim(ClaimTypes.Role, "DomainUser")
                }, "DomainUser");
                log.WriteLogEntry("Success create claims identity.");
                var TokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                {
                    Issuer             = Constants.Issuer,
                    Audience           = Constants.Audience,
                    Subject            = claimsID,
                    SigningCredentials = signatureCreds,
                };
                log.WriteLogEntry("Success create security token descriptor.");
                var plainToken = CreateToken(TokenDescriptor);
                log.WriteLogEntry("Plain token " + plainToken.ToString());
                string token = WriteToken(plainToken);
                log.WriteLogEntry("Encoded session token " + token);
                user.Token.SessionKey = token;
                result = true;
            }
            catch (Exception ex)
            {
                log.WriteLogEntry("ERROR generating JWT " + ex.Message);
                result = false;
            }
            log.WriteLogEntry("End GenerateDomainToken.");
            return(result);
        }
Beispiel #17
0
        static string GetJwtFromTokenIssuer()
        {
            byte[] key = Convert.FromBase64String("80ssGCKB931r2r8Lm3om1SIt5YY05yBZ34pna3+dYi8=");

            var symmetricKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key);
            //var symmetricKey = new InMemorySymmetricSecurityKey(key);

            var signingCredentials =
                new Microsoft.IdentityModel.Tokens.SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

            var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[]
            {
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny")
            });

            var descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject            = claimsIdentity,
                Audience           = "http://localhost:5000/api",
                Issuer             = "http://authzserver.demo",
                Expires            = DateTime.UtcNow.AddMinutes(1),
                SigningCredentials = signingCredentials
            };

            //var descriptor = new SecurityTokenDescriptor()
            //{
            //    TokenIssuerName = "http://authzserver.demo",
            //    AppliesToAddress = "http://localhost:5000/api",
            //    Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(1)),
            //    SigningCredentials = signingCredentials,
            //    Subject = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[]
            //    {
            //        new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny")
            //    })
            //};

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(descriptor);

            return(tokenHandler.WriteToken(token));
        }
Beispiel #18
0
        /// <summary>
        /// トークン作成メソッド_issuerがSCM1_AdminのJWTを生成する
        /// </summary>
        /// <param name="empid"></param>
        /// <returns></returns>
        public static bool CreateToken(string empid)
        {
            // 共通鍵を用意
            var dateKeyString = DateTime.Now.ToString();
            var keyString     = dateKeyString + FetchTokenPublicKeyString() + empid;
            // トークン操作用のクラスを用意
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            // 共通鍵なのでSymmetricSecurityKeyクラスを使う
            // 引数は鍵のバイト配列
            var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString));
            // 署名情報クラスを生成
            // 共通鍵を使うのでアルゴリズムはHS256使っとけばいいはず
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, "HS256");
            // トークンの詳細情報クラス?を生成
            var descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Issuer             = SCMIssuer,
                SigningCredentials = credentials,
            };
            // トークンの生成
            //SecurityTokenDescriptor使わずにhandler.CreateJwtSecurityToken("GHKEN", null, null, null, null, null, credentials)でもOK
            var token = handler.CreateJwtSecurityToken(descriptor);
            // トークンの文字列表現を取得
            var tokenString = handler.WriteToken(token);

            // トークンのDB保存
            try
            {
                //                ↓はxml内に記述されたSQLの「#」で括られた部分
                var param = new { ACCESS_TOKEN = tokenString, TOKEN_CREATE_DATE = dateKeyString, EMP_NO = empid };
                MST_EMP_Repository.StoreAccessToken_Repository(param);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            string userName = request["username"];
            string password = request["password"];

            bool isAuthentic = !String.IsNullOrEmpty(userName) && userName.Equals(password);

            if (isAuthentic)
            {
                // I use a hard-coded key
                byte[] key = Convert.FromBase64String("qqO5yXcbijtAdYmS2Otyzeze2XQedqy+Tp37wQ3sgTQ=");

                var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

                var descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                {
                    Issuer             = ISSUER,
                    Audience           = AUDIENCE,
                    Expires            = DateTime.UtcNow.AddMinutes(5),
                    SigningCredentials = signingCredentials,
                    Subject            = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, userName)
                    })
                };

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

                context.Response.Write(tokenHandler.WriteToken(token));
            }
            else
            {
                context.Response.StatusCode = 401;
            }
        }
Beispiel #20
0
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDTO)
        {
            // validate request
            var userFromRepo = await _repo.Login(userForLoginDTO.Username, userForLoginDTO.Password);

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

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

            var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

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

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

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
        public static Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor Convert( SecurityTokenDescriptor tokenDescriptor )
        {
            v1SecurityTokenDescriptor v1TokenDescriptor = new v1SecurityTokenDescriptor();

            if ( tokenDescriptor.AppliesToAddress != null )
                v1TokenDescriptor.AppliesToAddress = tokenDescriptor.AppliesToAddress;

            if ( tokenDescriptor.AttachedReference != null )
                v1TokenDescriptor.AttachedReference = tokenDescriptor.AttachedReference;

            if ( tokenDescriptor.AuthenticationInfo != null )
                v1TokenDescriptor.AuthenticationInfo = Convert(tokenDescriptor.AuthenticationInfo);

            if ( tokenDescriptor.Lifetime != null )
                v1TokenDescriptor.Lifetime = new Microsoft.IdentityModel.Protocols.WSTrust.Lifetime( tokenDescriptor.Lifetime.Created, tokenDescriptor.Lifetime.Expires );

            if ( tokenDescriptor.ReplyToAddress != null )
                v1TokenDescriptor.ReplyToAddress = tokenDescriptor.ReplyToAddress;

            if ( tokenDescriptor.SigningCredentials != null )
                v1TokenDescriptor.SigningCredentials = tokenDescriptor.SigningCredentials;

            if ( tokenDescriptor.Subject != null )
                v1TokenDescriptor.Subject = Convert( tokenDescriptor.Subject );

            if ( tokenDescriptor.TokenIssuerName != null )
                v1TokenDescriptor.TokenIssuerName = tokenDescriptor.TokenIssuerName;

            if ( tokenDescriptor.TokenType != null )
                v1TokenDescriptor.TokenType = tokenDescriptor.TokenType;

            return v1TokenDescriptor;
        }
Beispiel #22
0
        public Microsoft.AspNetCore.Mvc.IActionResult Login(ViewModels.Account.LoginViewModel viewModel)
        {
            // References:
            // https://jwt.io
            // https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/

            // Create Jwt Security Token Handler Object
            var jwtSecurityTokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            // **************************************************
            // Symmetric key must be atleast 128 bits long
            string strSymmetricKey = "This is the Symmetric Key";

            var symmetricSecurityKey =
                new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey
                    (System.Text.Encoding.ASCII.GetBytes(strSymmetricKey));

            var signingCredentials =
                new Microsoft.IdentityModel.Tokens.SigningCredentials
                    (key: symmetricSecurityKey,
                    algorithm: Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
            // **************************************************

            // Creating Token Description part
            var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject =
                    new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[]
                {
                    new System.Security.Claims.Claim("Username", "[Any Name]"),
                    new System.Security.Claims.Claim("RoleName", "[Any Role]"),
                    //new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "[Any Name]"),
                    //new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, "[Any Role]"),
                }),

                Issuer   = "[Token Issuer Name]",
                Audience = "http://www.IranianExperts.com",

                // define lifetime of the token
                Expires = System.DateTime.Now.AddMinutes(5),

                SigningCredentials = signingCredentials,
            };

            // Create Token
            var securityToken =
                jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);

            // convert Token to string
            string strTokenString =
                jwtSecurityTokenHandler.WriteToken(securityToken);

            var result = new
            {
                Token = strTokenString,
            };

            VerifyToken(strTokenString);

            //VerifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IltBbnkgTmFtZV0iLCJyb2xlIjoiW0FueSBSb2xlXSIsIm5iZiI6MTQ5MzU1MzAxOSwiZXhwIjoxNDkzNTUzMzE2LCJpYXQiOjE0OTM1NTMwMTksImlzcyI6IltUb2tlbiBJc3N1ZXIgTmFtZV0iLCJhdWQiOiJodHRwOi8vd3d3LklyYW5pYW5FeHBlcnRzLmNvbSJ9.zLgzHAUxoCsNLhC-nLkYyMhckD-uNop5JRM_m-PGz5o");
            // **************************************************

            return(Json(data: result,
                        serializerSettings: Infrastructure.JsonSerializerSettings.Instance));
        }
Beispiel #23
0
        public void ConfigureJwtAuthorizationFlow(string clientId, string userId, string oauthBasePath, string privateKeyFilename, int expiresInHours)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Expires = DateTime.UtcNow.AddHours(expiresInHours),
            };

            descriptor.Subject = new ClaimsIdentity();
            descriptor.Subject.AddClaim(new Claim("scope", "signature"));
            descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath));
            descriptor.Subject.AddClaim(new Claim("iss", clientId));

            if (userId != null)
            {
                descriptor.Subject.AddClaim(new Claim("sub", userId));
            }

            if (privateKeyFilename != null)
            {
                string pemKey = File.ReadAllText(privateKeyFilename);
                var    rsa    = CreateRSAKeyFromPem(pemKey);
                Microsoft.IdentityModel.Tokens.RsaSecurityKey rsaKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsa);
                descriptor.SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature);
            }

            var    token    = handler.CreateToken(descriptor);
            string jwtToken = handler.WriteToken(token);

            Uri baseUrl = this.RestClient.BaseUrl;

            this.RestClient.BaseUrl = new Uri(string.Format("https://{0}", oauthBasePath));

            string path        = "oauth/token";
            string contentType = "application/x-www-form-urlencoded";

            Dictionary <string, string> formParams = new Dictionary <string, string>();

            formParams.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
            formParams.Add("assertion", jwtToken);

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            Dictionary <string, string> headerParams = new Dictionary <string, string>();

            headerParams.Add("Content-Type", "application/x-www-form-urlencoded");

            Dictionary <string, FileParameter> fileParams = new Dictionary <string, FileParameter>();
            Dictionary <string, string>        pathParams = new Dictionary <string, string>();

            object postBody = null;

            try
            {
                var           response  = CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
                TokenResponse tokenInfo = JsonConvert.DeserializeObject <TokenResponse>(((RestResponse)response).Content);

                var config = Configuration.Default;
                config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token));
            }
            catch (Exception ex)
            {
            }

            this.RestClient.BaseUrl = baseUrl;
        }
        public async Task <ApplicationUser> Register(SignUpViewModel signUpViewModel)
        {
            ApplicationUser applicationUser = new ApplicationUser();

            applicationUser.FirstName          = signUpViewModel.PersonName.FirstName;
            applicationUser.LastName           = signUpViewModel.PersonName.LastName;
            applicationUser.Email              = signUpViewModel.Email;
            applicationUser.PhoneNumber        = signUpViewModel.Mobile;
            applicationUser.ReceiveNewsLetters = signUpViewModel.ReceiveNewsLetters;
            applicationUser.CountryID          = signUpViewModel.CountryID;
            applicationUser.Gender             = signUpViewModel.Gender;
            applicationUser.Role     = "Employee";
            applicationUser.UserName = signUpViewModel.Email;

            var result = await _applicationUserManager.CreateAsync(applicationUser, signUpViewModel.Password);

            if (result.Succeeded)
            {
                if ((await _applicationUserManager.AddToRoleAsync(await _applicationUserManager.FindByNameAsync(signUpViewModel.Email), "Employee")).Succeeded)
                {
                    var result2 = await _applicationSignInManager.PasswordSignInAsync(signUpViewModel.Email, signUpViewModel.Password, false, false);

                    if (result2.Succeeded)
                    {
                        //token
                        var tokenHandler    = new JwtSecurityTokenHandler();
                        var key             = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
                        var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                        {
                            Subject = new ClaimsIdentity(new Claim[] {
                                new Claim(ClaimTypes.Name, applicationUser.Id),
                                new Claim(ClaimTypes.Email, applicationUser.Email),
                                new Claim(ClaimTypes.Role, applicationUser.Role)
                            }),
                            Expires            = DateTime.UtcNow.AddHours(8),
                            SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        applicationUser.Token = tokenHandler.WriteToken(token);

                        //Skills
                        foreach (var sk in signUpViewModel.Skills)
                        {
                            Skill skill = new Skill();
                            skill.SkillName       = sk.SkillName;
                            skill.SkillLevel      = sk.SkillLevel;
                            skill.Id              = applicationUser.Id;
                            skill.ApplicationUser = null;
                            this._db.Skills.Add(skill);
                            this._db.SaveChanges();
                        }

                        return(applicationUser);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
        public static string GenerateJwtToken
            (Models.User user, ApplicationSettings.Main mainSettings)
        {
            // Generate token that is valid for 8 hours

            byte[] key =
                System.Text.Encoding.ASCII.GetBytes(mainSettings.SecretKey);

            var symmetricSecurityKey =
                new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key: key);

            var securityAlgorithm =
                Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature;

            var signingCredentials =
                new Microsoft.IdentityModel.Tokens
                .SigningCredentials(key: symmetricSecurityKey, algorithm: securityAlgorithm);

            var tokenDescriptor =
                new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject =
                    new System.Security.Claims.ClaimsIdentity
                        (new[]
                {
                    //new System.Security.Claims.Claim
                    //	(type: "RoleId", value: user.RoleId),

                    //new System.Security.Claims.Claim
                    //	(type: "LastName", value: user.LastName),

                    new System.Security.Claims.Claim
                        (type: nameof(user.LastName), value: user.LastName),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.Name, value: user.Username),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.Email, value: user.EmailAddress),

                    new System.Security.Claims.Claim
                        (type: System.Security.Claims.ClaimTypes.NameIdentifier, value: user.Id.ToString()),
                }),

                //Issuer = "",
                //Audience = "",

                //Expires =
                //	System.DateTime.UtcNow.AddHours(8),

                Expires =
                    System.DateTime.UtcNow.AddMinutes(mainSettings.TokenExpiresInMinutes),

                SigningCredentials = signingCredentials,
            };

            var tokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            Microsoft.IdentityModel.Tokens.SecurityToken
                securityToken = tokenHandler.CreateToken(tokenDescriptor: tokenDescriptor);

            string token =
                tokenHandler.WriteToken(token: securityToken);

            return(token);
        }