Exemplo n.º 1
0
        /// <summary>
        /// Cria a estrutura do token.
        /// </summary>
        /// <param name="authResult"></param>
        /// <returns></returns>
        internal static SecurityTokenDescriptor  CreateSecurityTokenDescriptor(AuthResult authResult)
        {
            if (_securityKey == null)
            {
                _securityKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ParameterCache.Get("TOKEN_SYMETRIC_KEY")));
            }


            int maxRole = authResult.UserRoles.Max(r => (int)r);

            var claimList = new List <System.Security.Claims.Claim>()
            {
                new System.Security.Claims.Claim(ClaimTypes.Sid, authResult.UserId.ToString()),
                new System.Security.Claims.Claim(ClaimTypes.Role, maxRole.ToString())
            };

            string smymetricKey = ParameterCache.Get("TOKEN_SYMETRIC_KEY");

            var now = DateTime.UtcNow;

            System.Security.Claims.Claim[] claims = claimList.ToArray();
            return(new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                TokenIssuerName = TOKEN_ISSUER,
                AppliesToAddress = TOKEN_AUDIENCE,
                Lifetime = new Lifetime(now, now.AddHours(TOKEN_EXPIRATION_HOURS)),
                SigningCredentials = new SigningCredentials(_securityKey,
                                                            "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                                                            "http://www.w3.org/2001/04/xmlenc#sha256"),
            });
        }
        /// <summary>
        /// Initializes the session token manager with the signing key bytes
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task Init()
        {
            // Guard that ensures Init is executed once only
            lock (this.locker)
            {
                if (this.initStarted == true)
                {
                    return;
                }

                this.initStarted = true;
            }

            string hashingKeyUrl = await this.connectionStringProvider.GetHashingKey();

            string signingKeyValue = await this.kv.GetSecretByUrlAsync(hashingKeyUrl);

            byte[] signingKeyBytes = Encoding.UTF8.GetBytes(signingKeyValue);

            if (signingKeyBytes == null)
            {
                throw new ArgumentNullException("Session token manager cannot take a null signing key.");
            }

            if (signingKeyBytes.Length != 32)
            {
                throw new ArgumentException("Signing key must be 32 bytes in length.");
            }

            this.signingKey = new InMemorySymmetricSecurityKey(signingKeyBytes);

            // Init done
            this.initDone.Set();
        }
Exemplo n.º 3
0
        private string CreateToken(UserData userData)
        {
            var signingKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JwtPrivateKey"]));

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

            var claimsIdentity = new ClaimsIdentity(new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userData.Id.ToString()),
                new Claim(ClaimTypes.Surname, userData.LastName),
                new Claim(ClaimTypes.Name, userData.FirstName),
                new Claim(ClaimTypes.Email, userData.Email),
                new Claim(ClaimTypes.MobilePhone, userData.MobileNumber),
            }, "normalUser");

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                AppliesToAddress   = ConfigurationManager.AppSettings["ValidAudience"],
                TokenIssuerName    = ConfigurationManager.AppSettings["ValidIssuer"],
                Subject            = claimsIdentity,
                SigningCredentials = signingCredentials,
                Lifetime           = new Lifetime(DateTime.Now, DateTime.Now.AddHours(2))
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var plainToken   = tokenHandler.CreateToken(securityTokenDescriptor);

            return(tokenHandler.WriteToken(plainToken));
        }
Exemplo n.º 4
0
        public void CreateTokenAndParseEncodedMultipleClaims()
        {
            var handler = new SimpleWebTokenHandler();

            byte[] key         = GetKey();
            var    token       = this.CreateToken(key);
            var    tokenString = TokenToString(token);
            var    signedToken = handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var symmetricKey = new InMemorySymmetricSecurityKey(key);

            handler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
                new Uri("http://audience"));

            var resolverTable = new Dictionary <string, IList <SecurityKey> >
            {
                { "http://issuer", new SecurityKey[] { symmetricKey } }
            };

            handler.Configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var ids = handler.ValidateToken(signedToken);
            var id  = ids.FirstOrDefault();

            Assert.IsNotNull(id);

            var testClaims = GetClaims();

            Assert.IsTrue(id.Claims.Count() == 3);
            Assert.IsTrue(id.HasClaim(testClaims[0].Type, testClaims[0].Value));
            Assert.IsTrue(id.HasClaim(testClaims[1].Type, testClaims[1].Value));
            Assert.IsTrue(id.HasClaim(testClaims[2].Type, testClaims[2].Value));
        }
Exemplo n.º 5
0
        public object Login(TokenRequest request)
        {
            string signKey  = ConfigurationManager.AppSettings["SignKey"];
            string issuer   = ConfigurationManager.AppSettings["Issuer"];
            string audience = ConfigurationManager.AppSettings["Audience"];

            if (request.Username == "Jon" && request.Password == "123")
            {
                var claims = new[]
                {
                    //自訂payload附帶其他Identity其他屬性的type & value map宣告
                    new Claim(ClaimTypes.Name, request.Username),
                    new Claim(ClaimTypes.Role, "AdminRole")
                };

                var key   = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

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

                return(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                });

                ;
            }

            return(BadRequest("Could not verify username and password"));
        }
Exemplo n.º 6
0
        private InMemorySymmetricSecurityKey GetSigningKey()
        {
            var plainTextSecurityKey = "a1cb0802-b821-4f6e-a7d8-a1351e888c52";
            var signingKey           = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));

            return(signingKey);
        }
Exemplo n.º 7
0
        private TokenValidationParameters GetTokenValidationParameters()
        {
            var signingKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JwtPrivateKey"]));

            return(new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings["ValidAudience"],

                ValidIssuer = ConfigurationManager.AppSettings["ValidIssuer"],

                IssuerSigningKey = signingKey
            });
        }