Exemplo n.º 1
0
        /// <summary>
        /// This methos validates the Simple Web Token.
        /// </summary>
        /// <param name="token">A simple web token.</param>
        /// <returns>A Claims Collection which contains all the claims from the token.</returns>
        public ClaimsIdentityCollection ValidateToken(SecurityToken token, string key)
        {
            SimpleWebToken realToken = token as SimpleWebToken;

            if (realToken == null)
            {
                throw new InvalidTokenReceivedException("The received token is of incorrect token type.Expected SimpleWebToken");
            }

            if (realToken.AudienceUri != OAuthConfiguration.Configuration.ServiceSettings.Realm)
            {
                throw new InvalidTokenReceivedException("The Audience Uri of the incoming token is not expected. Expected AudienceUri is " + OAuthConfiguration.Configuration.ServiceSettings.Realm);
            }

            if (StringComparer.OrdinalIgnoreCase.Compare(realToken.Issuer, OAuthConfiguration.Configuration.StsSettings.IssuerUri.ToString()) != 0)
            {
                throw new InvalidTokenReceivedException("The Issuer of the token is not trusted. Trusted issuer is " + OAuthConfiguration.Configuration.StsSettings.IssuerUri);
            }

            if (!realToken.SignVerify(Convert.FromBase64String(key)))
            {
                throw new InvalidTokenReceivedException("Signature verification of the incoming token failed.");
            }

            if (DateTime.Compare(realToken.ValidTo, DateTime.UtcNow) <= 0)
            {
                throw new ExpiredTokenReceivedException("The incoming token has expired. Get a new access token from the Authorization Server.");
            }

            ClaimsIdentityCollection identities = new ClaimsIdentityCollection();
            ClaimsIdentity           identity   = new ClaimsIdentity();

            foreach (var claim in realToken.Claims)
            {
                identity.Claims.Add(claim);
            }

            identities.Add(identity);

            return(identities);
        }
Exemplo n.º 2
0
        // POST api/issue
        public HttpResponseMessage Post(TokenRequest rst)
        {
            Uri scope = rst.Scope;

            if (scope == null)
            {
                return Request.CreateResponse<TokenResponse>(HttpStatusCode.BadRequest, new TokenResponse() { Error = OAuthError.INVALID_REQUEST });
            }

            string key = OAuthConfiguration.Configuration.StsSettings.SymmetricKey;
            TimeSpan lifeTime = new TimeSpan(0, 0, OAuthConfiguration.Configuration.StsSettings.TokenLifeTimeInSec); 

            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, this.User.Identity.Name));
            claims.Add(new Claim(ClaimTypes.Role, "AssetsServiceUser"));
            claims.Add(new Claim(ClaimTypes.Role, "Developer"));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator"));

            SimpleWebToken token = new SimpleWebToken(scope, OAuthConfiguration.Configuration.StsSettings.IssuerUri.ToString(), DateTime.UtcNow + lifeTime, claims, key);

            var tokenResponse = new TokenResponse() { AccessToken = token.ToString(), TokenType = "bearer", ExpiresIn = 600 };
            return Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Reads a serialized token and converts it into a <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="rawToken">The token in serialized form.</param>
        /// <returns>The parsed form of the token.</returns>
        public SecurityToken ReadToken(string rawToken)
        {
            char parameterSeparator = '&';
            Uri audienceUri = null;
            string issuer = null;
            string signature = null;
            string unsignedString = null;
            string expires = null;

            if (string.IsNullOrEmpty(rawToken))
            {
                throw new ArgumentNullException("rawToken");
            }

            //
            // Find the last parameter. The signature must be last per SWT specification.
            //
            int lastSeparator = rawToken.LastIndexOf(parameterSeparator);

            // Check whether the last parameter is an hmac.
            //
            if (lastSeparator > 0)
            {
                string lastParamStart = parameterSeparator + SwtConst.Digest256Label + "=";
                string lastParam = rawToken.Substring(lastSeparator);
                signature = lastParam.Replace(lastParamStart, "");

                // Strip the trailing hmac to obtain the original unsigned string for later hmac verification.
                // e.g. name1=value1&name2=value2&HMACSHA256=XXX123 -> name1=value1&name2=value2
                //
                if (signature != null && lastParam.StartsWith(lastParamStart, StringComparison.Ordinal))
                {
                    unsignedString = rawToken.Substring(0, lastSeparator);
                }
                else
                {
                    throw new InvalidTokenReceivedException("Then incoming token does not have a signature");
                }
            }
            else
            {
                throw new InvalidTokenReceivedException("The Simple Web Token must have a signature at the end. The incoming token did not have a signature at the end of the token.");
            }

            // Signature is a mandatory parameter, and it must be the last one.
            // If there's no trailing hmac, Return error.
            //
            if (unsignedString == null)
            {
                throw new InvalidTokenReceivedException("The Simple Web Token must have a signature at the end. The incoming token did not have a signature at the end of the token.");
            }

            // Create a collection of SWT claims
            //
            NameValueCollection rawClaims = ParseToken(unsignedString);

            audienceUri = new Uri(rawClaims[SwtConst.AudienceLabel]);
            if (audienceUri != null)
            {
                rawClaims.Remove(SwtConst.AudienceLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an AudienceUri.");
            }

            expires = rawClaims[SwtConst.ExpiresOnLabel];
            if (expires != null)
            {
                rawClaims.Remove(SwtConst.ExpiresOnLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an expiry time.");
            }

            issuer = rawClaims[SwtConst.IssuerLabel];
            if (issuer != null)
            {
                rawClaims.Remove(SwtConst.IssuerLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an Issuer");
            }

            List<Claim> claims = DecodeClaims(issuer, rawClaims);

            SimpleWebToken swt = new SimpleWebToken(audienceUri, issuer, DecodeExpiry(expires), claims, signature, unsignedString);
            return swt;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Reads a serialized token and converts it into a <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="rawToken">The token in serialized form.</param>
        /// <returns>The parsed form of the token.</returns>
        public SecurityToken ReadToken(string rawToken)
        {
            char   parameterSeparator = '&';
            Uri    audienceUri        = null;
            string issuer             = null;
            string signature          = null;
            string unsignedString     = null;
            string expires            = null;

            if (string.IsNullOrEmpty(rawToken))
            {
                throw new ArgumentNullException("rawToken");
            }

            //
            // Find the last parameter. The signature must be last per SWT specification.
            //
            int lastSeparator = rawToken.LastIndexOf(parameterSeparator);

            // Check whether the last parameter is an hmac.
            //
            if (lastSeparator > 0)
            {
                string lastParamStart = parameterSeparator + SwtConst.Digest256Label + "=";
                string lastParam      = rawToken.Substring(lastSeparator);
                signature = lastParam.Replace(lastParamStart, "");

                // Strip the trailing hmac to obtain the original unsigned string for later hmac verification.
                // e.g. name1=value1&name2=value2&HMACSHA256=XXX123 -> name1=value1&name2=value2
                //
                if (signature != null && lastParam.StartsWith(lastParamStart, StringComparison.Ordinal))
                {
                    unsignedString = rawToken.Substring(0, lastSeparator);
                }
                else
                {
                    throw new InvalidTokenReceivedException("Then incoming token does not have a signature");
                }
            }
            else
            {
                throw new InvalidTokenReceivedException("The Simple Web Token must have a signature at the end. The incoming token did not have a signature at the end of the token.");
            }

            // Signature is a mandatory parameter, and it must be the last one.
            // If there's no trailing hmac, Return error.
            //
            if (unsignedString == null)
            {
                throw new InvalidTokenReceivedException("The Simple Web Token must have a signature at the end. The incoming token did not have a signature at the end of the token.");
            }

            // Create a collection of SWT claims
            //
            NameValueCollection rawClaims = ParseToken(unsignedString);

            audienceUri = new Uri(rawClaims[SwtConst.AudienceLabel]);
            if (audienceUri != null)
            {
                rawClaims.Remove(SwtConst.AudienceLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an AudienceUri.");
            }

            expires = rawClaims[SwtConst.ExpiresOnLabel];
            if (expires != null)
            {
                rawClaims.Remove(SwtConst.ExpiresOnLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an expiry time.");
            }

            issuer = rawClaims[SwtConst.IssuerLabel];
            if (issuer != null)
            {
                rawClaims.Remove(SwtConst.IssuerLabel);
            }
            else
            {
                throw new InvalidTokenReceivedException("Then incoming token does not have an Issuer");
            }

            List <Claim> claims = DecodeClaims(issuer, rawClaims);

            SimpleWebToken swt = new SimpleWebToken(audienceUri, issuer, DecodeExpiry(expires), claims, signature, unsignedString);

            return(swt);
        }