/// <summary>
        /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class specifying optional parameters.
        /// </summary>
        /// <param name="issuer">if this value is not null, a { iss, 'issuer' } claim will be added.</param>
        /// <param name="audience">if this value is not null, a { aud, 'audience' } claim will be added</param>
        /// <param name="claims">if this value is not null then for each <see cref="Claim"/> a { 'Claim.Type', 'Claim.Value' } is added. If duplicate claims are found then a { 'Claim.Type', List&lt;object> } will be created to contain the duplicate values.</param>
        /// <param name="expires">if expires.HasValue a { exp, 'value' } claim is added.</param>
        /// <param name="notBefore">if notbefore.HasValue a { nbf, 'value' } claim is added.</param>
        /// <param name="signingCredentials">The <see cref="SigningCredentials"/> that will be used to sign the <see cref="JwtSecurityToken"/>. See <see cref="JwtHeader(SigningCredentials)"/> for details pertaining to the Header Parameter(s).</param>
        /// <exception cref="ArgumentException">if 'expires' &lt;= 'notbefore'.</exception>
        public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable <Claim> claims = null, DateTime?notBefore = null, DateTime?expires = null, SigningCredentials signingCredentials = null)
        {
            if (expires.HasValue && notBefore.HasValue)
            {
                if (notBefore >= expires)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10401, expires.Value, notBefore.Value));
                }
            }

            this.payload = new JwtPayload(issuer: issuer, audience: audience, claims: claims, notBefore: notBefore, expires: expires);
            this.header  = new JwtHeader(signingCredentials);
        }
        /// <summary>
        /// Decodes the string into the header, payload and signature
        /// </summary>
        /// <param name="jwtEncodedString">Base64Url encoded string.</param>
        internal void Decode(string jwtEncodedString)
        {
            string[] tokenParts = jwtEncodedString.Split(new char[] { '.' }, 4);
            if (tokenParts.Length != 3)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString));
            }

            try
            {
                this.header = JwtHeader.Base64UrlDeserialize(tokenParts[0]);

                // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0"
                string type = this.header.Typ;
                if (type != null)
                {
                    if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt)))
                    {
                        throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10702, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type));
                    }
                }
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "header", tokenParts[0], jwtEncodedString), ex);
            }

            try
            {
                this.payload = JwtPayload.Base64UrlDeserialize(tokenParts[1]);
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "payload", tokenParts[1], jwtEncodedString), ex);
            }

            this.rawData      = jwtEncodedString;
            this.rawHeader    = tokenParts[0];
            this.rawPayload   = tokenParts[1];
            this.rawSignature = tokenParts[2];
        }
示例#3
0
        /// <summary>
        /// Decodes the string into the header, payload and signature
        /// </summary>
        /// <param name="jwtEncodedString">Base64Url encoded string.</param>
        internal void Decode(string jwtEncodedString)
        {
            string[] tokenParts = jwtEncodedString.Split('.');
            if (tokenParts.Length != 3)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10400, "jwtEncodedString", jwtEncodedString));
            }

            try
            {
                this.header = Base64UrlEncoder.Decode(tokenParts[0]).DeserializeJwtHeader();

                // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0"
                string type = null;
                if (this.header.TryGetValue(JwtConstants.ReservedHeaderParameters.Type, out type))
                {
                    if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt)))
                    {
                        throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10112, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type));
                    }
                }
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10113, "header", tokenParts[0], jwtEncodedString), ex);
            }

            try
            {
                this.payload = Base64UrlEncoder.Decode(tokenParts[1]).DeserializeJwtPayload();
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10113, "payload", tokenParts[1], jwtEncodedString), ex);
            }

            this.rawData   = jwtEncodedString;
            this.signature = tokenParts[2];
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the encoded <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. The jwtEncodedString is the result of those operations.
        /// </summary>
        /// <param name="header">Contains JSON objects representing the cryptographic operations applied to the JWT and optionally any additional properties of the JWT</param>
        /// <param name="payload">Contains JSON objects representing the claims contained in the JWT. Each claim is a JSON object of the form { Name, Value }</param>
        /// <exception cref="ArgumentNullException">'header' is null.</exception>
        /// <exception cref="ArgumentNullException">'payload' is null.</exception>
        public JwtSecurityToken(JwtHeader header, JwtPayload payload)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }

            this.header  = header;
            this.payload = payload;
        }
示例#5
0
        public string GenerateJwtToken(string issuer, string audience, IEnumerable <Claim> claims, DateTime?notBefore, DateTime?expires)
        {
            string audienceSecreteKey = GlobalConstants.JwtTopSecrete512;

            string audienceSecreteBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(audienceSecreteKey));

            byte[] audienceSecrete = Convert.FromBase64String(audienceSecreteBase64);

            SymmetricSecurityKey securityKey        = new InMemorySymmetricSecurityKey(audienceSecrete);
            SigningCredentials   signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);  // HmacSha256: to be able to debug @jwt.io but you can go higher

            JwtPayload payload = new JwtPayload(issuer, audience, claims, notBefore, expires);

            System.IdentityModel.Tokens.JwtHeader        header        = new System.IdentityModel.Tokens.JwtHeader(signingCredentials);
            System.IdentityModel.Tokens.JwtSecurityToken securityToken = new System.IdentityModel.Tokens.JwtSecurityToken(header, payload);

            return(this.jwtSecurityTokenHandler.WriteToken(securityToken));
        }
示例#6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the encoded <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. The jwtEncodedString is the result of those operations.
        /// </summary>
        /// <param name="header">Contains JSON objects representing the cryptographic operations applied to the JWT and optionally any additional properties of the JWT</param>
        /// <param name="payload">Contains JSON objects representing the claims contained in the JWT. Each claim is a JSON object of the form { Name, Value }</param>
        /// <param name="jwtEncodedString">The results of encoding and applying the cryptographic operations to the <see cref="JwtHeader"/> and <see cref="JwtPayload"/>.</param>
        /// <exception cref="ArgumentNullException">'header' is null.</exception>
        /// <exception cref="ArgumentNullException">'payload' is null.</exception>
        /// <exception cref="ArgumentNullException">'jwtEncodedString' is null.</exception>
        /// <exception cref="ArgumentException">'jwtEncodedString' contains only whitespace.</exception>
        /// <exception cref="ArgumentException">'jwtEncodedString' is not in JWS Compact serialized format.</exception>
        public JwtSecurityToken(JwtHeader header, JwtPayload payload, string jwtEncodedString)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }

            if (jwtEncodedString == null)
            {
                throw new ArgumentNullException("jwtEncodedString");
            }

            if (string.IsNullOrWhiteSpace(jwtEncodedString))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, WifExtensionsErrors.WIF10002, "jwtEncodedString"));
            }

            if (!Regex.IsMatch(jwtEncodedString, JwtConstants.JsonCompactSerializationRegex))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10400, "jwtEncodedString", jwtEncodedString));
            }

            string[] tokenParts = jwtEncodedString.Split('.');
            if (tokenParts.Length != 3)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10400, "jwtEncodedString", jwtEncodedString));
            }

            this.header    = header;
            this.payload   = payload;
            this.rawData   = jwtEncodedString;
            this.signature = tokenParts[2];
        }
示例#7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class specifying optional parameters.
 /// </summary>
 /// <param name="issuer">if this value is not null, a { iss, 'issuer' } claim will be added.</param>
 /// <param name="audience">if this value is not null, a { aud, 'audience' } claim will be added</param>
 /// <param name="claims">if this value is not null then for each <see cref="Claim"/> a { 'Claim.Type', 'Claim.Value' } is added. If duplicate claims are found then a { 'Claim.Type', List&lt;object> } will be created to contain the duplicate values.</param>
 /// <param name="lifetime">if this value is not null, then if <para><see cref="Lifetime" />.Created.HasValue a { nbf, 'value' } is added.</para><para>if <see cref="Lifetime"/>.Expires.HasValue a { exp, 'value' } claim is added.</para></param>
 /// <param name="signingCredentials">The <see cref="SigningCredentials"/> that will be or was used to sign the <see cref="JwtSecurityToken"/>. See <see cref="JwtHeader(SigningCredentials)"/> for details pertaining to the Header Parameter(s).</param>
 public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable <Claim> claims = null, Lifetime lifetime = null, SigningCredentials signingCredentials = null)
 {
     this.payload = new JwtPayload(issuer, audience, claims, lifetime);
     this.header  = new JwtHeader(signingCredentials);
 }