public virtual string WriteTokenAsString(System.IdentityModel.Tokens.SecurityToken token)
        {
            Utility.VerifyNonNullArgument("token", token);
            JsonWebSecurityToken jsonWebSecurityToken = token as JsonWebSecurityToken;

            if (jsonWebSecurityToken == null)
            {
                throw new System.ArgumentException("Unsupported token type", "token");
            }
            if (jsonWebSecurityToken.CanWriteSourceData)
            {
                return(jsonWebSecurityToken.WriteSourceData());
            }
            System.Collections.Generic.IDictionary <string, string> self  = jsonWebSecurityToken.CreateHeaderClaims();
            System.Collections.Generic.IDictionary <string, string> self2 = jsonWebSecurityToken.CreatePayloadClaims();
            string text = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", new object[]
            {
                Base64UrlEncoder.Encode(self.EncodeToJson()),
                Base64UrlEncoder.Encode(self2.EncodeToJson())
            });
            string text2 = this.Sign(text, jsonWebSecurityToken.SigningCredentials);

            return(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", new object[]
            {
                text,
                text2
            }));
        }
        private ClaimsIdentityCollection ValidateTokenCore(System.IdentityModel.Tokens.SecurityToken token, bool isActorToken)
        {
            JsonWebSecurityToken jsonWebSecurityToken = token as JsonWebSecurityToken;

            if (jsonWebSecurityToken == null)
            {
                return(base.ValidateToken(token));
            }
            if (base.Configuration == null)
            {
                throw new System.InvalidOperationException("No configuration.");
            }
            if (base.Configuration.IssuerNameRegistry == null)
            {
                throw new System.InvalidOperationException("No issuername registry configured.");
            }
            this.ValidateLifetime(jsonWebSecurityToken);
            this.ValidateAudience(jsonWebSecurityToken);
            System.IdentityModel.Tokens.X509SecurityToken x509SecurityToken = jsonWebSecurityToken.IssuerToken as System.IdentityModel.Tokens.X509SecurityToken;
            if (x509SecurityToken != null)
            {
                base.Configuration.CertificateValidator.Validate(x509SecurityToken.Certificate);
            }
            ClaimsIdentityCollection claimsIdentityCollection = new ClaimsIdentityCollection();
            ClaimsIdentity           claimsIdentity           = new ClaimsIdentity("Federation");

            if (!isActorToken && jsonWebSecurityToken.ActorToken != null)
            {
                ValidateActorTokenForAppOnly(jsonWebSecurityToken.ActorToken);
                ClaimsIdentityCollection claimsIdentityCollection2 = this.ValidateActorToken(jsonWebSecurityToken.ActorToken);
                if (claimsIdentityCollection2.Count > 1)
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenException("Invalid JWT token. Actor has multiple identities.");
                }
                claimsIdentity.Actor = claimsIdentityCollection2[0];
            }
            string issuerName = this.GetIssuerName(jsonWebSecurityToken);

            foreach (JsonWebTokenClaim current in jsonWebSecurityToken.Claims)
            {
                if (claimsIdentity.Actor == null || !System.StringComparer.Ordinal.Equals("actortoken", current.ClaimType))
                {
                    string text = current.Value;
                    if (text == null)
                    {
                        text = "NULL";
                    }
                    claimsIdentity.Claims.Add(new Claim(current.ClaimType, text, "http://www.w3.org/2001/XMLSchema#string", issuerName));
                }
            }
            if (!isActorToken && base.Configuration.SaveBootstrapTokens)
            {
                claimsIdentity.BootstrapToken = token;
            }
            claimsIdentityCollection.Add(claimsIdentity);
            return(claimsIdentityCollection);
        }
 /// <summary>
 ///Validates that the actor token is an app token by checking for the lack of user claims
 /// </summary>
 /// <param name="actorToken"></param>
 private static void ValidateActorTokenForAppOnly(JsonWebSecurityToken actorToken)
 {
     if (actorToken != null)
     {
         if (actorToken.Claims.FirstOrDefault <JsonWebTokenClaim>(x => x.ClaimType.Equals("scp")) != null ||
             actorToken.Claims.FirstOrDefault <JsonWebTokenClaim>(x => x.ClaimType.Equals("upn")) != null ||
             actorToken.Claims.FirstOrDefault <JsonWebTokenClaim>(x => x.ClaimType.Equals("unique_name")) != null ||
             actorToken.Claims.FirstOrDefault <JsonWebTokenClaim>(x => x.ClaimType.Equals("altsecid")) != null)
         {
             throw new UnauthorizedAccessException("Invalid actor token.");
         }
     }
 }
        protected virtual string GetIssuerName(JsonWebSecurityToken token)
        {
            if (token.IssuerToken == null)
            {
                throw new System.IdentityModel.Tokens.SecurityTokenException("JWT tokens must be signed.");
            }
            string issuerName = base.Configuration.IssuerNameRegistry.GetIssuerName(token.IssuerToken, token.Issuer);

            if (string.IsNullOrEmpty(issuerName))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenException("Invalid issuer or signature.");
            }
            return(issuerName);
        }
 protected virtual void ValidateAudience(JsonWebSecurityToken token)
 {
     if (base.Configuration.AudienceRestriction.AudienceMode == System.IdentityModel.Selectors.AudienceUriMode.Always || base.Configuration.AudienceRestriction.AudienceMode == System.IdentityModel.Selectors.AudienceUriMode.BearerKeyOnly)
     {
         if (string.IsNullOrEmpty(token.Audience))
         {
             throw new Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException("Audience URI validation failed. Token audience must be specified.");
         }
         AudienceValidator.ValidateAudiences(base.Configuration.AudienceRestriction.AllowedAudienceUris, new System.Uri[]
         {
             new System.Uri(token.Audience, System.UriKind.RelativeOrAbsolute)
         });
     }
 }
        public override System.IdentityModel.Tokens.SecurityToken ReadToken(System.Xml.XmlReader reader)
        {
            if (!this.CanReadToken(reader))
            {
                throw new System.Xml.XmlException("Unsupported security token.");
            }
            string id = null;
            string jsonTokenString = this.GetJsonTokenString(reader, out id);
            JsonWebSecurityToken jsonWebSecurityToken = this.ReadToken(jsonTokenString) as JsonWebSecurityToken;

            if (jsonWebSecurityToken != null)
            {
                jsonWebSecurityToken.SetId(id);
            }
            return(jsonWebSecurityToken);
        }
        private JsonWebSecurityToken ReadActor(System.Collections.Generic.IDictionary <string, string> payload)
        {
            if (!this.JsonWebSecurityTokenRequirement.AllowActorToken)
            {
                return(null);
            }
            JsonWebSecurityToken result = null;
            string text;

            payload.TryGetValue("actortoken", out text);
            if (!string.IsNullOrEmpty(text))
            {
                result = (this.ReadTokenCore(text, true) as JsonWebSecurityToken);
                payload.Remove("actortoken");
            }
            return(result);
        }
 protected virtual void ValidateLifetime(JsonWebSecurityToken token)
 {
     System.TimeSpan maxClockSkew = base.Configuration.MaxClockSkew;
     System.DateTime utcNow       = System.DateTime.UtcNow;
     if (maxClockSkew < System.TimeSpan.Zero)
     {
         throw new System.InvalidOperationException("No valid ClockSkew configured.");
     }
     if (token.ValidTo < utcNow - maxClockSkew)
     {
         throw new Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException("Invalid JWT token. The token is expired.");
     }
     if (token.ValidFrom > utcNow + maxClockSkew)
     {
         throw new Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException(string.Concat(new object[]
         {
             "Invalid JWT token. The token is not yet valid. Current time is ",
             utcNow,
             " and the token is Valid from ",
             token.ValidFrom,
             "."
         }));
     }
 }
 protected virtual ClaimsIdentityCollection ValidateActorToken(JsonWebSecurityToken actorToken)
 {
     return(this.ValidateTokenCore(actorToken, true));
 }
        private System.IdentityModel.Tokens.SecurityToken ReadTokenCore(string token, bool isActorToken)
        {
            Utility.VerifyNonNullOrEmptyStringArgument("token", token);
            if (base.Configuration == null)
            {
                throw new System.InvalidOperationException("No configuration");
            }
            if (base.Configuration.IssuerTokenResolver == null)
            {
                throw new System.InvalidOperationException("No configured IssuerTokenResolver");
            }
            if (!this.CanReadToken(token))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenException("Unsupported security token.");
            }
            string[] array = token.Split(new char[]
            {
                '.'
            });
            string text  = array[0];
            string text2 = array[1];
            string text3 = array[2];

            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>(System.StringComparer.Ordinal);
            dictionary.DecodeFromJson(Base64UrlEncoder.Decode(text));
            System.Collections.Generic.Dictionary <string, string> dictionary2 = new System.Collections.Generic.Dictionary <string, string>(System.StringComparer.Ordinal);
            dictionary2.DecodeFromJson(Base64UrlEncoder.Decode(text2));
            string text4;

            dictionary.TryGetValue("alg", out text4);
            System.IdentityModel.Tokens.SecurityToken issuerToken = null;
            if (!System.StringComparer.Ordinal.Equals(text4, "none"))
            {
                if (string.IsNullOrEmpty(text3))
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenException("Missing signature.");
                }
                System.IdentityModel.Tokens.SecurityKeyIdentifier signingKeyIdentifier = this.GetSigningKeyIdentifier(dictionary, dictionary2);
                System.IdentityModel.Tokens.SecurityToken         securityToken;
                base.Configuration.IssuerTokenResolver.TryResolveToken(signingKeyIdentifier, out securityToken);
                if (securityToken == null)
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenException("Invalid JWT token. Could not resolve issuer token.");
                }
                issuerToken = this.VerifySignature(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                {
                    text,
                    text2
                }), text3, text4, securityToken);
            }
            JsonWebSecurityToken actorToken = null;

            if (!isActorToken)
            {
                actorToken = this.ReadActor(dictionary2);
            }
            string text5;

            dictionary2.TryGetValue("iss", out text5);
            if (string.IsNullOrEmpty(text5))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenValidationException("The token being parsed does not have an issuer.");
            }
            string text6;

            dictionary2.TryGetValue("aud", out text6);
            if (string.IsNullOrEmpty(text6))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenValidationException("The token being parsed does not have an audience.");
            }
            string text7;

            dictionary2.TryGetValue("nbf", out text7);
            if (string.IsNullOrEmpty(text7))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenValidationException("The token being parsed does not have an 'not before' claim.");
            }
            System.DateTime dateTimeFromSeconds = this.GetDateTimeFromSeconds(text7);
            text7 = "";
            dictionary2.TryGetValue("exp", out text7);
            if (string.IsNullOrEmpty(text7))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenValidationException("The token being parsed does not have an 'expires at' claim.");
            }
            System.DateTime      dateTimeFromSeconds2 = this.GetDateTimeFromSeconds(text7);
            JsonWebSecurityToken jsonWebSecurityToken = new JsonWebSecurityToken(text5, text6, dateTimeFromSeconds, dateTimeFromSeconds2, this.CreateClaims(dictionary2), issuerToken, actorToken);

            jsonWebSecurityToken.CaptureSourceData(token);
            return(jsonWebSecurityToken);
        }
Example #11
0
 public JsonWebSecurityToken(string issuer, string audience, System.DateTime validFrom, System.DateTime validTo, System.Collections.Generic.IEnumerable <JsonWebTokenClaim> claims, System.IdentityModel.Tokens.SecurityToken issuerToken, JsonWebSecurityToken actorToken) : this(issuer, audience, validFrom, validTo, claims)
 {
     this._issuerToken = issuerToken;
     this._actorToken  = actorToken;
 }