Example #1
0
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
        public void RoundTrip(List <Claim> claims, JwtPayload payloadSetDirect, JwtPayload payloadSetUsingDeserialize)
        {
            var context             = new CompareContext();
            var payload             = new JwtPayload(claims);
            var encodedPayload      = payload.SerializeToJson();
            var payloadDeserialized = JwtPayload.Deserialize(encodedPayload);
            var instanceContext     = new CompareContext();

            IdentityComparer.AreEqual(payload, payloadDeserialized, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "AreEqual({0}, {1})", nameof(payload), nameof(payloadDeserialized)), instanceContext);

            instanceContext = new CompareContext();
            IdentityComparer.AreEqual(payload, payloadSetDirect, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "AreEqual({0}, {1})", nameof(payload), nameof(payloadSetDirect)), instanceContext);

            instanceContext = new CompareContext();
            IdentityComparer.AreEqual(payload, payloadSetUsingDeserialize, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "AreEqual({0}, {1})", nameof(payload), nameof(payloadSetUsingDeserialize)), instanceContext);

            instanceContext.Diffs.Clear();
            IdentityComparer.AreEqual(payload.Claims, claims, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "AreEqual({0}, {1})", nameof(payload.Claims), nameof(claims)), instanceContext);

            instanceContext.Diffs.Clear();
            CheckClaimsTypeParsing(payload.Claims, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "CheckClaimsTypeParsing({0})", nameof(payload.Claims)), instanceContext);

            instanceContext.Diffs.Clear();
            CheckClaimsTypeParsing(payloadDeserialized.Claims, instanceContext);
            context.Merge(string.Format(CultureInfo.InvariantCulture, "CheckClaimsTypeParsing({0})", nameof(payloadDeserialized.Claims)), instanceContext);

            TestUtilities.AssertFailIfErrors(context);
        }
Example #2
0
        public ViewResult GenerateToken(string jsontext, string key, string algorithm)
        {
            try
            {
                jsontext = jsontext.Replace("\r", String.Empty);
                jsontext = jsontext.Replace("\n", String.Empty);
                var json = JsonConvert.DeserializeObject(jsontext);
                //KEY (your - 256 - bit - secret )
                var verificarion = Encoding.UTF8.GetBytes(key);

                var sKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
                var signingcredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(sKey, algorithm);
                //HEADER
                var header = new JwtHeader(signingcredential);
                //PAYLOAD
                var payload = new JwtPayload();
                payload = JwtPayload.Deserialize(jsontext);

                var            secToken    = new JwtSecurityToken(header, payload);
                var            handler     = new JwtSecurityTokenHandler();
                var            tokenString = handler.WriteToken(secToken);
                AlgorithmModel model       = new AlgorithmModel();
                model.token = tokenString;
                return(View(model));
            }
            catch
            {
                ViewBag.Message = "Please enter a valid key";
                return(View(new AlgorithmModel()));
            }
        }
        public string Get(string cadena)
        {
            string[] data     = cadena.Split('|');
            User     userdata = new User();

            userdata.name     = data[0];
            userdata.password = data[1];
            string jsontext = JsonConvert.SerializeObject(userdata);

            jsontext = jsontext.Replace("\r", String.Empty);
            jsontext = jsontext.Replace("\n", String.Empty);
            var sKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(data[2]));
            var signingcredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(sKey, "HS256");
            //HEADER
            var header = new JwtHeader(signingcredential);
            //PAYLOAD
            var payload = new JwtPayload();

            payload = JwtPayload.Deserialize(jsontext);
            var    secToken    = new JwtSecurityToken(header, payload);
            var    handler     = new JwtSecurityTokenHandler();
            var    tokenString = handler.WriteToken(secToken);
            string token       = tokenString;

            return(token);
        }
Example #4
0
        public virtual bool ValidateChangeEmailToken(string token, out int userId, out string email)
        {
            try
            {
                var tokenDecrypted = cryptService.Decrypt(CipherSecrets.EmailChange, token);

                var jwtSecurityToken = new JwtSecurityToken(new JwtHeader(), JwtPayload.Deserialize(tokenDecrypted));

                email  = jwtSecurityToken.Claims.First(x => x.Type == JwtRegisteredClaimNames.Email).Value;
                userId = int.Parse(jwtSecurityToken.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value);

                if (jwtSecurityToken.ValidTo.Add(TokensExpiration.Delta) < DateTime.UtcNow)
                {
                    return(false);
                }
            }
            catch
            {
                email  = null;
                userId = 0;
                return(false);
            }

            return(true);
        }
        public async Task <bool> ConfirmRegisterAsync(string token)
        {
            string userId;

            try
            {
                var tokenDecrypt = await jwtService.DecryptEmailToken(token);

                var jweToken = new JwtSecurityToken(new JwtHeader(), JwtPayload.Deserialize(tokenDecrypt));

                userId = jweToken.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;

                if (jweToken.ValidTo < DateTime.UtcNow)
                {
                    return(false);
                }

                var updateResult = await userProvider.ConfirmUserRegisterAsync(userId);

                if (updateResult)
                {
                    return(true);
                }
            }
            catch
            {
            }
            return(false);
        }
        /// <summary>
        /// Validates that an OpenIdConnect Response from "useinfo_endpoint" is valid as per http://openid.net/specs/openid-connect-core-1_0.html
        /// </summary>
        /// <param name="validationContext">the <see cref="OpenIdConnectProtocolValidationContext"/> that contains expected values.</param>
        /// <exception cref="ArgumentNullException">If 'validationContext' is null.</exception>
        /// <exception cref="OpenIdConnectProtocolException">If the response is not spec compliant.</exception>
        public virtual void ValidateUserInfoResponse(OpenIdConnectProtocolValidationContext validationContext)
        {
            if (validationContext == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(validationContext));
            }

            if (string.IsNullOrEmpty(validationContext.UserInfoEndpointResponse))
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogMessages.IDX21337));
            }

            if (validationContext.ValidatedIdToken == null)
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogMessages.IDX21332));
            }

            string sub = string.Empty;

            try
            {
                // if user info response is a jwt token
                var handler = new JwtSecurityTokenHandler();
                if (handler.CanReadToken(validationContext.UserInfoEndpointResponse))
                {
                    var token = handler.ReadToken(validationContext.UserInfoEndpointResponse) as JwtSecurityToken;
                    sub = token.Payload.Sub;
                }
                else
                {
                    // if the response is not a jwt, it should be json
                    var payload = JwtPayload.Deserialize(validationContext.UserInfoEndpointResponse);
                    sub = payload.Sub;
                }
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogHelper.FormatInvariant(LogMessages.IDX21343, validationContext.UserInfoEndpointResponse), ex));
            }

            if (string.IsNullOrEmpty(sub))
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogMessages.IDX21345));
            }

            if (string.IsNullOrEmpty(validationContext.ValidatedIdToken.Payload.Sub))
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogMessages.IDX21346));
            }

            if (!string.Equals(validationContext.ValidatedIdToken.Payload.Sub, sub, StringComparison.Ordinal))
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogHelper.FormatInvariant(LogMessages.IDX21338, validationContext.ValidatedIdToken.Payload.Sub, sub)));
            }
        }
Example #7
0
        private Task <string> SignAsync(string payload, SigningCredentials credentials)
        {
            var header     = CreateHeader(credentials);
            var jwtPayload = JwtPayload.Deserialize(payload);

            var token = new JwtSecurityToken(header, jwtPayload);

            var handler = new JwtSecurityTokenHandler();

            return(Task.FromResult(handler.WriteToken(token)));
        }
Example #8
0
        public JwtSecurityToken ReadLong2Token(string token)
        {
            var tokenDecrypted = cryptService.Decrypt(CipherSecrets.Long2Jwt, token);

            var jwtSecurityToken = new JwtSecurityToken(new JwtHeader(), JwtPayload.Deserialize(tokenDecrypted));

            if (jwtSecurityToken.ValidTo.Add(TokensExpiration.Delta) < DateTime.UtcNow)
            {
                throw new Exception("Long2 token expires");
            }

            return(jwtSecurityToken);
        }
Example #9
0
        /// <summary>
        /// Builds a claims identity.
        /// </summary>
        /// <param name="request">The incoming <see cref="HttpRequest" />.</param>
        /// <returns>A populated <see cref="ClaimsIdentity" />.</returns>
        public Task <ClaimsIdentity> BuildClaimsIdentityAsync(HttpRequest request)
        {
            ClaimsIdentity result = null;

            if (request.Headers.ContainsKey(HeaderKey))
            {
                var jwtPayload = JwtPayload.Deserialize(request.Headers[HeaderKey]);

                result = new ClaimsIdentity(jwtPayload.Claims, "marainclaims", "name", "roles");
            }

            return(Task.FromResult(result));
        }
Example #10
0
        public ClaimsPrincipal ReadShortToken(string token)
        {
            var tokenDecrypted = cryptService.Decrypt(CipherSecrets.ShortJwt, token);

            JwtSecurityToken jwtSecurityToken =
                new JwtSecurityToken(new JwtHeader(), JwtPayload.Deserialize(tokenDecrypted));

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(jwtSecurityToken.Claims, SunJwt.Scheme);

            if (jwtSecurityToken.ValidTo.Add(TokensExpiration.Delta) < DateTime.UtcNow)
            {
                throw new Exception("Short token expires");
            }

            return(new ClaimsPrincipal(claimsIdentity));
        }
Example #11
0
        public async Task <object> PremiumInfo()
        {
            string accessTokenOnAggregator = premiumInfoValidationService.CheckAndGetAccessTokenOnAggregator(Request);
            string atHash = HelperHash.AtHashString(accessTokenOnAggregator);

            var authorizationState = await authorizationStateService.GetAuthStateByTokenAsync(atHash);

            var servingOperator = idgwConnectorManager.GetServingOperatorByString(authorizationState !.PremiumInfoToken.ServingOperator !);
            var idgwConnector   = idgwConnectorManager[servingOperator];

            var idgwResponse = await idgwConnector !.PremiumInfoAsync(authorizationState !.PremiumInfoToken.AccessTokenOnIdgw !);
            var idgwJwks     = await idgwConnector.GetJwksAsync();

            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

            if (jwtSecurityTokenHandler.CanReadToken(idgwResponse))
            {
                if (!JwtSignatureValidator.Validate(idgwResponse, idgwJwks, out var idClaims))
                {
                    throw new UnifiedException(OAuth2Error.UnauthorizedClient);
                }
                var jwtPayload = jwtSecurityTokenHandler.ReadJwtToken(idgwResponse).Payload;

                if (authorizationState !.IsPremiumInfoSigned)
                {
                    return(SignedJwtCreator.Create(jwtPayload, settings.PrivateKey !));
                }
                return(jwtPayload);
            }

            if (authorizationState !.IsPremiumInfoSigned)
            {
                var newPayload = JwtPayload.Deserialize(idgwResponse);

                return(SignedJwtCreator.Create(newPayload, settings.PrivateKey !));
            }
            var idgwResponseJson = JsonDocument.Parse(idgwResponse);

            if (idgwResponseJson != null)
            {
                return(idgwResponseJson);
            }
            return(idgwResponse);
        }
        public virtual UserInfo RecoverUserInfoFromIdentityServer(string accessToken)
        {
            //
            // request for id_token
            var userInfoResponse = HttpClientFactory.Instance.GetUserInfoAsync(new UserInfoRequest
            {
                Address = Configuration.UserInfoEndpoint,
                Token   = accessToken,
            }).Result;

            if (userInfoResponse.IsError)
            {
                throw new InvalidOperationException($"Identity Server returned invalid user info (id_token) from '{Configuration.UserInfoEndpoint}' response '{userInfoResponse.Raw}'");
            }

            //
            // recover user info
            var payload = JwtPayload.Deserialize(userInfoResponse.Raw);

            return(RecoverUserInfoFromJwtPayload(payload));
        }
Example #13
0
        public ActionResult Get()
        {
            //var clamis = new Claim[] {
            //    new Claim("client_id","ClientCredentials"),
            //    new Claim("client_Role","admin"),
            //    new Claim("client_Name","zhngsan"),
            //};
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("k762ynnzhzW7m8CFZ90cYIiQVhD/Ljiraosr03wXfUo="));
            //var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //var token2 = new JwtSecurityToken(
            //     "issuer", "audience", clamis, DateTime.Now, DateTime.Now.AddHours(1), creds
            //    );

            var creds2 = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
            var head   = new JwtHeader(creds2);
            //var head = JwtHeader.Deserialize(Newtonsoft.Json.JsonConvert.SerializeObject(new {
            //    alg = "RS256",
            //    kid = "5e03711d37e07f5190f00bb260a5209f",
            //    typ = "JWT",
            //    SigningCredentials=new SigningCredentials(key,"12344")

            //}));
            var body = JwtPayload.Deserialize(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                nbf         = 1550725910,
                exp         = 1550729510,
                iss         = "http://localhost:5000",
                aud         = new string[] { "http://localhost:5000/resources", "api1" },
                client_id   = "ClientCredentials",
                client_Role = "admin",
                client_Name = "zhangsan",
                scope       = new string[] { "api1" }
            }));
            var token = new JwtSecurityToken(
                head, body
                );

            return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }));
            //return new string[] { "value1", "value2" };
        }
Example #14
0
        public void JwtPayloadUnicodeMapping()
        {
            string       issuer         = "a\\b";
            List <Claim> claims         = new List <Claim>();
            JwtPayload   unicodePayload = new JwtPayload("a\u005Cb", "", claims, null, null);
            string       json           = unicodePayload.SerializeToJson();
            JwtPayload   payload        = new JwtPayload(issuer, "", claims, null, null);
            string       json2          = payload.SerializeToJson();

            Assert.Equal(json, json2);

            JwtPayload retrievePayload = JwtPayload.Deserialize(json);

            Assert.Equal(retrievePayload.Iss, issuer);

            json  = unicodePayload.Base64UrlEncode();
            json2 = payload.Base64UrlEncode();
            Assert.Equal(json, json2);

            retrievePayload = JwtPayload.Base64UrlDeserialize(json);
            Assert.Equal(retrievePayload.Iss, issuer);
        }
Example #15
0
        private static void SetDataSet(List <Claim> claims, TheoryData <List <Claim>, JwtPayload, JwtPayload> dataset)
        {
            var payloadDirect = new JwtPayload();
            var jobj          = new JObject();

            foreach (var claim in claims)
            {
                object jsonValue = null;
                object existingValue;
                switch (claim.ValueType)
                {
                case ClaimValueTypes.String:
                    jsonValue = claim.Value;
                    break;

                case ClaimValueTypes.Boolean:
                    jsonValue = bool.Parse(claim.Value);
                    break;

                case ClaimValueTypes.Double:
                    jsonValue = double.Parse(claim.Value);
                    break;

                case ClaimValueTypes.Integer:
                case ClaimValueTypes.Integer32:
                    jsonValue = int.Parse(claim.Value);
                    break;

                case ClaimValueTypes.Integer64:
                    jsonValue = long.Parse(claim.Value);
                    break;

                case JsonClaimValueTypes.Json:
                    jsonValue = JObject.Parse(claim.Value);
                    break;

                case JsonClaimValueTypes.JsonArray:
                    jsonValue = JArray.Parse(claim.Value);
                    break;
                }

                JToken jtoken = null;
                if (jobj.TryGetValue(claim.Type, out jtoken))
                {
                    JArray jarray = jtoken as JArray;
                    if (jarray == null)
                    {
                        jarray = new JArray();
                        jarray.Add(jtoken);
                        jobj.Remove(claim.Type);
                        jobj.Add(claim.Type, jarray);
                    }

                    jarray.Add(JToken.FromObject(jsonValue));
                }
                else
                {
                    jobj.Add(claim.Type, JToken.FromObject(jsonValue));
                }

                if (payloadDirect.TryGetValue(claim.Type, out existingValue))
                {
                    IList <object> claimValues = existingValue as IList <object>;
                    if (claimValues == null)
                    {
                        claimValues = new List <object>();
                        claimValues.Add(existingValue);
                        payloadDirect[claim.Type] = claimValues;
                    }

                    claimValues.Add(jsonValue);
                }
                else
                {
                    payloadDirect[claim.Type] = jsonValue;
                }
            }

            var j = jobj.ToString(Formatting.None);
            var payloadDeserialized = JwtPayload.Deserialize(j);

            dataset.Add(claims, payloadDirect, payloadDeserialized);
        }
Example #16
0
        public static async Task <AccessTokenResponse> GetClientAccessToken(this HttpClient httpClient,
                                                                            string clientName, RSAParameters rsaParameters, IEnumerable <string> scopes = null)
        {
            var fullAddress = httpClient.BaseAddress;

            if (fullAddress.PathAndQuery != "" && !fullAddress.PathAndQuery.EndsWith("/"))
            {
                fullAddress = new Uri(fullAddress + "/");
            }

            var audience = fullAddress + "connect/token";
            var jwt      = CreateClientAssertionJwt(audience, clientName, rsaParameters);


            var properties = new Dictionary <string, string>
            {
                ["grant_type"]            = "client_credentials",
                ["client_id"]             = clientName,
                ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
                ["client_assertion"]      = jwt
            };

            var scopesArray = (scopes ?? Array.Empty <string>()).ToArray();

            if (scopesArray.Any())
            {
                properties.Add("scopes", string.Join(",", scopesArray.Select(x => x)));
            }

            var request = new HttpRequestMessage(HttpMethod.Post, audience)
            {
                Content = new FormUrlEncodedContent(properties)
            };

            var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead)
                           .ConfigureAwait(false);

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            try
            {
                var payload = JwtPayload.Deserialize(content);
                if (payload.TryGetValue("error", out _))
                {
                    throw new InvalidOperationException();
                }

                payload.TryGetValue("access_token", out var accessToken);
                payload.TryGetValue("expires_in", out var expiresIn);
                payload.TryGetValue("scope", out var scopesResponse);

                var tokenResponse = new AccessTokenResponse
                {
                    AccessToken = accessToken?.ToString(),
                    ExpiresOn   = expiresIn == null
                        ? default
                        : DateTimeOffset.UtcNow.AddSeconds(Convert.ToInt32(expiresIn)),
                    Scopes = scopesResponse?.ToString().Split(',')
                };


                return(tokenResponse);
            }
            catch
            {
                throw new InvalidOperationException("An error occurred while retrieving an access token.");
            }
        }