public async Task FailsWhenWrongOwnerCredentialsProvided(string username, string password)
        {
            var server = new OAuth2TestServer(s =>
            {
                LookupClient(s.Provider, "one", null, null);
                s.Provider.OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials("the-username", "the-password");
            });

            LastLookupClientId.ShouldBe(null);

            string body = "grant_type=password&client_id=one";

            if (username != null)
            {
                body += "&username="******"&password="******"https://example.com/token",
                postBody : body);

            LastLookupClientId.ShouldBe("one");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_grant");
        }
Exemple #2
0
        public async Task CodeCanBeUsedOnlyOneTime()
        {
            var server = new OAuth2TestServer(s =>
            {
                s.Options.AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(8);
                s.Options.AccessTokenExpireTimeSpan       = TimeSpan.FromSeconds(655321);
                s.OnAuthorizeEndpoint = SignInEpsilon;
            });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code");

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha");

            transaction2.ResponseToken["access_token"].Value <string>().ShouldNotBe(null);
            transaction2.ResponseToken["token_type"].Value <string>().ShouldBe("bearer");
            transaction2.ResponseToken["expires_in"].Value <long>().ShouldBe(655321);

            OAuth2TestServer.Transaction transaction3 = await server.SendAsync("https://example.com/token",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha");

            transaction3.ResponseToken["error"].Value <string>().ShouldBe("invalid_grant");
        }
        public async Task TokenMayBeIssuedToClient()
        {
            var server = new OAuth2TestServer(s =>
            {
                s.Provider.OnGrantClientCredentials = ctx =>
                {
                    var claims = new List <Claim>
                    {
                        new Claim(ClaimsIdentity.DefaultNameClaimType, ctx.ClientId),
                    };
                    string scope = string.Join(" ", ctx.Scope);
                    if (!string.IsNullOrEmpty(scope))
                    {
                        claims.Add(new Claim("scope", scope));
                    }
                    ctx.Validated(new ClaimsIdentity(claims, "Bearer"));
                    return(Task.FromResult(0));
                };
            });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
                postBody : "grant_type=client_credentials");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            var accessToken = transaction1.ResponseToken.Value <string>("access_token");

            string userName = await GetUserName(server, accessToken);

            userName.ShouldBe("alpha");
        }
        private async Task <string> GetUserName(OAuth2TestServer server, string accessToken)
        {
            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/me",
                                                                              authenticateHeader : new AuthenticationHeaderValue("Bearer", accessToken));

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            return(transaction.ResponseText);
        }
Exemple #5
0
        public async Task IncorrectRedirectUriDoesNotRedirect()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&redirect_uri=" + Uri.EscapeDataString("http://wrongplace.com/"));

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction.ResponseText.ShouldContain("invalid_request");
        }
Exemple #6
0
        public async Task MissingClientIdDoesNotRedirect()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction.ResponseText.ShouldContain("invalid_request");
        }
Exemple #7
0
        public async Task MissingResponseTypeRedirectsWithErrorMessage()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
            transaction.Response.Headers.Location.Query.ShouldContain("error=invalid_request");
        }
        public async Task BadClientIdDoesNotRedirect()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=wrong");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseText.ShouldContain("invalid_request");
        }
Exemple #9
0
        public async Task UnsupportedResponseTypeRedirectsWithErrorMessage()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=delta");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
            transaction.Response.Headers.Location.Query.ShouldContain("error=unsupported_response_type");
        }
        public async Task MissingClientCredentialsFails()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                postBody : "grant_type=client_credentials");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
        public async Task StateShouldBePassedBack()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=alpha&state=123");

            NameValueCollection fragment = transaction1.ParseRedirectFragment();

            fragment.Get("access_token").ShouldNotBe(null);
            fragment.Get("state").ShouldBe("123");
        }
        public async Task ShouldRedirectWithParametersInFragment()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));

            NameValueCollection fragment = transaction1.ParseRedirectFragment();

            fragment.Get("access_token").ShouldNotBe(null);
            fragment.Get("expires_in").ShouldNotBe(null);
        }
        public async Task MissingClientCredentialsFails()
        {
            var server = new OAuth2TestServer(s => { s.Provider.OnGrantCustomExtension = ValidateCustomGrant; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                postBody : "grant_type=urn:example:register");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
        public async Task UnrecognizedClientCredentialsFails()
        {
            var server = new OAuth2TestServer(s => { s.Provider.OnGrantCustomExtension = ValidateCustomGrant; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("bad:data"))),
                postBody : "grant_type=urn:example:register");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
        public async Task BadUtf8ClientCredentialsFails()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(new byte[] { 0x8F, 0x90 })),
                postBody : "grant_type=client_credentials");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
        public async Task NonPermittedClientFails()
        {
            var server = new OAuth2TestServer();

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
                postBody : "grant_type=client_credentials");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("unauthorized_client");
        }
        public async Task UnrecognizedParametersAreIgnored()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?alpha=beta&response_type=token&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));

            NameValueCollection fragment = transaction1.ParseRedirectFragment();

            string userName = await GetUserName(server, fragment.Get("access_token"));

            userName.ShouldBe("epsilon");
        }
Exemple #18
0
        public async Task CodeFlowWillFailIfRedirectUriOriginallyIncorrect()
        {
            var server = new OAuth2TestServer(s =>
            {
                s.Options.AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
                s.Options.AccessTokenExpireTimeSpan       = TimeSpan.FromMinutes(60);
                s.OnAuthorizeEndpoint = SignInEpsilon;
            });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma2.com/return"));

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
        }
Exemple #19
0
        public async Task CodeFlowFailsWhenConfidentialClientDoesNotProvideCredentials()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code");

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha");

            transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction2.ResponseToken["error"].Value <string>().ShouldBe("invalid_client");
        }
Exemple #20
0
        public async Task CodeFlowFailsWhenPublicClientDoesProvideCredentials()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha3&response_type=code");

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha3:beta3"))),
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha3");

            transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction2.ResponseToken["error"].Value <string>().ShouldBe("invalid_client");
        }
        public async Task AccessTokenMayBeUsed()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));

            NameValueCollection fragment = transaction1.ParseRedirectFragment();
            string accessToken           = fragment.Get("access_token");

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/me",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Bearer", accessToken));

            transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            transaction2.ResponseText.ShouldBe("epsilon");
        }
Exemple #22
0
        public async Task CodeFlowRedirectUriMustMatch()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha&redirect_uri=");

            transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction2.ResponseToken["error"].Value <string>().ShouldBe("invalid_grant");
        }
        public async Task ResourceOwnerFailsWithoutClientWhenNotExplicitlyEnabled()
        {
            var server = new OAuth2TestServer(s =>
            {
                LookupClient(s.Provider, "one", null, null);
                s.Provider.OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials("the-username", "the-password");
            });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                postBody : "grant_type=password&username=the-username&password=the-password");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
        public async Task TokenMayBeIssuedWithCustomGrantType()
        {
            var server = new OAuth2TestServer(s => { s.Provider.OnGrantCustomExtension = ValidateCustomGrant; });

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                authenticateHeader : new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha2:beta2"))),
                postBody : "grant_type=urn:example:register&alias=one");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            var accessToken = transaction1.ResponseToken.Value <string>("access_token");

            string userName = await GetUserName(server, accessToken);

            userName.ShouldBe("one");
        }
Exemple #25
0
        public async Task CallingSignInWillRedirectWithAuthorizationCode()
        {
            var server = new OAuth2TestServer
            {
                OnAuthorizeEndpoint = ctx =>
                {
                    ctx.Authentication.SignIn(new AuthenticationProperties(), CreateIdentity("epsilon"));
                    return(Task.FromResult <object>(null));
                }
            };

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
            transaction.Response.Headers.Location.Query.ShouldContain("code=");
        }
Exemple #26
0
        public async Task CodeCanBeExchangedForToken()
        {
            var server = new OAuth2TestServer
            {
                OnAuthorizeEndpoint = SignInEpsilon
            };

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha3&response_type=code");

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token", postBody :
                                                                               "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha3");

            transaction2.ResponseToken["access_token"].Value <string>().ShouldNotBe(null);
            transaction2.ResponseToken["token_type"].Value <string>().ShouldBe("bearer");
        }
Exemple #27
0
        public async Task NonTwoHundredDoesNotGetChanged()
        {
            var server = new OAuth2TestServer
            {
                OnAuthorizeEndpoint = ctx =>
                {
                    ctx.Response.StatusCode = 404;
                    ctx.Authentication.SignIn(
                        new AuthenticationProperties(),
                        CreateIdentity("epsilon"));
                    return(Task.FromResult <object>(null));
                }
            };

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
            transaction.Response.Headers.Location.ShouldBe(null);
        }
        public async Task FailsWhenWrongPasswordProvided()
        {
            var server = new OAuth2TestServer(s =>
            {
                LookupClient(s.Provider, "one", "two", "https://example.com/return");
                s.Provider.OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials("the-username", "the-password");
            });

            LastLookupClientId.ShouldBe(null);

            OAuth2TestServer.Transaction transaction1 = await server.SendAsync(
                "https://example.com/token",
                postBody : "grant_type=password&username=the-username&password=the-password&client_id=one");

            LastLookupClientId.ShouldBe("one");

            transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            transaction1.ResponseToken.Value <string>("error").ShouldBe("invalid_client");
        }
Exemple #29
0
        public async Task AuthorizeRequestMayPassThroughToApplicationRequestHandler()
        {
            var server = new OAuth2TestServer
            {
                OnAuthorizeEndpoint = async ctx =>
                {
                    ctx.Response.ContentType = "text/plain";
                    using (var writer = new StreamWriter(ctx.Response.Body, Encoding.UTF8, 4096, leaveOpen: true))
                    {
                        await writer.WriteAsync("Responding");
                    }
                }
            };

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code");

            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            transaction.ResponseText.ShouldBe("Responding");
        }
Exemple #30
0
        public async Task CodeFlowSucceedsWhenPublicClientDoesNotProvideCredentials()
        {
            var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });

            OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha3&response_type=code");

            NameValueCollection query = transaction.ParseRedirectQueryString();

            OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
                                                                               postBody : "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha3");

            var accessToken = transaction2.ResponseToken["access_token"].Value <string>();

            OAuth2TestServer.Transaction transaction3 = await server.SendAsync("https://example.com/me",
                                                                               authenticateHeader : new AuthenticationHeaderValue("Bearer", accessToken));

            transaction3.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            transaction3.ResponseText.ShouldBe("epsilon");
        }