コード例 #1
0
        public static bool IsIdentityRecognized(TokenIdentification identification)
        {
            var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var filePath = Path.Combine(basePath.Substring(6), LoginDirectory, LoginFile);

            string validUsername, validPassword;

            using (StreamReader r = File.OpenText(filePath))
            {
                string json = r.ReadToEnd();
                TokenIdentification credentials = JsonConvert.DeserializeObject <TokenIdentification>(json);
                validUsername = EncryptionHelper.Decrypt(credentials.Username);
                validPassword = EncryptionHelper.Decrypt(credentials.Password);
            }

            if (identification.Username.Equals(validUsername) && identification.Password.Equals(validPassword))
            {
                return(true);
            }

            return(false);
        }
コード例 #2
0
        public static string GenerateToken(TokenIdentification identification, int expireMinutes = 20)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var now             = DateTime.UtcNow;
            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, identification.Username)
                }),

                Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),

                SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature)
            };

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

            return(token);
        }
コード例 #3
0
        public IHttpActionResult GenerateToken([FromBody] TokenIdentification identification)
        {
            if (!ModelState.IsValid || identification == null || identification.Username == null || identification.Password == null)
            {
                return(BadRequest());
            }

            var recognized = TokenManager.IsIdentityRecognized(identification);

            if (!recognized)
            {
                return(BadRequest("Not recognized."));
            }

            var token = TokenManager.GenerateToken(identification);

            if (token == null)
            {
                return(BadRequest("Invalid token."));
            }

            return(Ok(token));
        }