Example #1
0
        private static string?GetClaimsChallenge(Response response)
        {
            if (response.Status != (int)HttpStatusCode.Unauthorized || !response.Headers.TryGetValue(ChallengeHeader, out string?headerValue))
            {
                return(null);
            }

            ReadOnlySpan <char> bearer     = "Bearer".AsSpan();
            ReadOnlySpan <char> claims     = "claims".AsSpan();
            ReadOnlySpan <char> headerSpan = headerValue.AsSpan();

            // Iterate through each challenge value.
            while (TryGetNextChallenge(ref headerSpan, out var challengeKey))
            {
                // Enumerate each key=value parameter until we find the 'claims' key on the 'Bearer' challenge.
                while (TryGetNextParameter(ref headerSpan, out var key, out var value))
                {
                    if (challengeKey.Equals(bearer, StringComparison.OrdinalIgnoreCase) && key.Equals(claims, StringComparison.OrdinalIgnoreCase))
                    {
                        return(Base64Url.DecodeString(value.ToString()));
                    }
                }
            }

            return(null);
        }
Example #2
0
        public static PerformanceInformation CreateFromHeaderString(string headerValue)
        {
            var jsonValue = Base64Url.DecodeString(headerValue);

            return(JsonConvert.DeserializeObject <PerformanceInformation>(jsonValue, new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
        }
Example #3
0
        public void ValidateEncodeDecodeStringZeroLength()
        {
            var data = string.Empty;

            var encoded = Base64Url.EncodeString(data);

            Assert.AreEqual(string.Empty, encoded);

            var decoded = Base64Url.DecodeString(encoded);

            Assert.AreEqual(data, decoded);
        }
Example #4
0
        protected override bool AuthorizeRequestOnChallenge(HttpMessage message)
        {
            var challenge = AuthorizationChallengeParser.GetChallengeParameterFromResponse(message.Response, "Bearer", "claims");

            if (challenge == null)
            {
                return(false);
            }

            string claimsChallenge = Base64Url.DecodeString(challenge);
            var    context         = new TokenRequestContext(_scopes, message.Request.ClientRequestId, claimsChallenge);

            AuthenticateAndAuthorizeRequest(message, context);
            return(true);
        }
        protected override async ValueTask <bool> AuthenticateRequestOnChallengeAsync(HttpMessage message, bool async)
        {
            var challenge = AuthorizationChallengeParser.GetChallengeParameterFromResponse(message.Response, "Bearer", "claims");

            if (challenge == null)
            {
                return(false);
            }

            string claimsChallenge = Base64Url.DecodeString(challenge.ToString());
            var    context         = new TokenRequestContext(Scopes, message.Request.ClientRequestId, claimsChallenge);

            await SetAuthorizationHeader(message, context, async);

            return(true);
        }
Example #6
0
        protected override bool TryGetTokenRequestContextFromChallenge(HttpMessage message, out TokenRequestContext context)
        {
            context = default;

            var challenge = AuthorizationChallengeParser.GetChallengeParameterFromResponse(message.Response, "Bearer", "claims");

            if (challenge == null)
            {
                return(false);
            }

            string claimsChallenge = Base64Url.DecodeString(challenge.ToString());

            context = new TokenRequestContext(Scopes, message.Request.ClientRequestId, claimsChallenge);
            return(true);
        }
Example #7
0
        public void ValidateEncodeDecodeStringRandom()
        {
            var seed = new Random().Next();

            var rand = new Random(seed);

            for (int i = 1; i <= 512; i++)
            {
                for (int j = 0; j < 32; j++)
                {
                    var data = GenerateRandomString(rand, i);

                    var encoded = Base64Url.EncodeString(data);

                    var decoded = Base64Url.DecodeString(encoded);

                    Assert.AreEqual(data, decoded, "String round trip failed. Seed {0}", seed);
                }
            }
        }
Example #8
0
        internal static JwtPayload DecodeJwtPayload(string token)
        {
            const string TokenNotFormattedCorrectly = "Token is not formatted correctly.";

            var tokenParts = token.Split('.');

            if (tokenParts.Length < 2)
            {
                throw new FormatException(TokenNotFormattedCorrectly);
            }

            try
            {
                return(JsonSerializer.Deserialize <JwtPayload>(Base64Url.DecodeString(tokenParts[1])));
            }
            catch (JsonException ex)
            {
                throw new FormatException(TokenNotFormattedCorrectly, ex);
            }
        }
Example #9
0
        /// <inheritdoc/>
        public override StoredAttestationPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (typeToConvert != typeof(StoredAttestationPolicy))
            {
                throw new InvalidOperationException();
            }

            string serializedObject = string.Empty;

            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new JsonException();
            }
            reader.Read();

            if (reader.TokenType != JsonTokenType.PropertyName)
            {
                throw new JsonException("Expected property name in StoredAttestationPolicy.");
            }

            string fieldName = reader.GetString();

            if (fieldName != "AttestationPolicy")
            {
                throw new JsonException($"Expected property name AttestationPolicy, found {fieldName}.");
            }
            reader.Read();

            string fieldValue = reader.GetString();

            reader.Read();

            if (reader.TokenType != JsonTokenType.EndObject)
            {
                throw new JsonException();
            }
            reader.Read();
            return(new StoredAttestationPolicy {
                AttestationPolicy = Base64Url.DecodeString(fieldValue)
            });
        }
Example #10
0
        public static PerformanceInformation CreateFromHeaderString(string headerValue)
        {
            var jsonValue = Base64Url.DecodeString(headerValue);

            return(JsonConvert.DeserializeObject <PerformanceInformation>(jsonValue));
        }
        public async Task ValidateClaimsChallengeTokenRequest()
        {
            string currentClaimChallenge = null;

            int tokensRequested = 0;

            var credential = new TokenCredentialStub((r, c) =>
            {
                tokensRequested++;

                Assert.AreEqual(currentClaimChallenge, r.Claims);

                return(new AccessToken(Guid.NewGuid().ToString(), DateTimeOffset.UtcNow + TimeSpan.FromDays(1)));
            }, IsAsync);

            var policy = new ARMChallengeAuthenticationPolicy(credential, "scope");

            var insufficientClaimsChallengeResponse = new MockResponse(401);

            insufficientClaimsChallengeResponse.AddHeader(new HttpHeader("WWW-Authenticate", CaeInsufficientClaimsChallenge));

            var sessionRevokedChallengeResponse = new MockResponse(401);

            sessionRevokedChallengeResponse.AddHeader(new HttpHeader("WWW-Authenticate", CaeSessionsRevokedClaimsChallenge));

            var armChallengeResponse = new MockResponse(401);

            armChallengeResponse.AddHeader(new HttpHeader("WWW-Authenticate", ArmChallenge));

            var keyvaultChallengeResponse = new MockResponse(401);

            keyvaultChallengeResponse.AddHeader(new HttpHeader("WWW-Authenticate", KeyVaultChallenge));

            MockTransport transport = CreateMockTransport(new MockResponse(200),
                                                          insufficientClaimsChallengeResponse,
                                                          new MockResponse(200),
                                                          sessionRevokedChallengeResponse,
                                                          new MockResponse(200),
                                                          armChallengeResponse,
                                                          keyvaultChallengeResponse);

            var response = await SendGetRequest(transport, policy, uri : new Uri("https://example.com"), cancellationToken : default);

            Assert.AreEqual(tokensRequested, 1);

            Assert.AreEqual(response.Status, 200);

            currentClaimChallenge = Base64Url.DecodeString(CaeInsufficientClaimsChallengeValue);

            response = await SendGetRequest(transport, policy, uri : new Uri("https://example.com"), cancellationToken : default);

            Assert.AreEqual(tokensRequested, 2);

            Assert.AreEqual(response.Status, 200);

            currentClaimChallenge = Base64Url.DecodeString(CaeSessionsRevokedClaimsChallengeValue);

            response = await SendGetRequest(transport, policy, uri : new Uri("https://example.com"), cancellationToken : default);

            Assert.AreEqual(tokensRequested, 3);

            Assert.AreEqual(response.Status, 200);

            currentClaimChallenge = null;

            response = await SendGetRequest(transport, policy, uri : new Uri("https://example.com"), cancellationToken : default);

            Assert.AreEqual(tokensRequested, 3);

            Assert.AreEqual(response.Status, 401);

            response = await SendGetRequest(transport, policy, uri : new Uri("https://example.com"), cancellationToken : default);

            Assert.AreEqual(tokensRequested, 3);

            Assert.AreEqual(response.Status, 401);
        }