private void WvLogin_Navigating(object sender, WebNavigatingEventArgs e)
        {
            if (e.Url.Contains("https://xamarin-oidc-sample/redirect"))
            {
                wvLogin.IsVisible = false;

                // parse response
                _authResponse = new AuthorizeResponse(e.Url);

                // CSRF check
                var state = _authResponse.Values["state"];
                if (state != _currentCSRFToken)
                {
                    txtResult.Text = "CSRF token doesn't match";
                    return;
                }

                string decodedTokens = "";
                // decode tokens
                if (!string.IsNullOrWhiteSpace(_authResponse.IdentityToken))
                {
                    decodedTokens += "Identity token \r\n";
                    decodedTokens += DecodeToken(_authResponse.IdentityToken) + "\r\n";
                }

                if (!string.IsNullOrWhiteSpace(_authResponse.AccessToken))
                {
                    decodedTokens += "Access token \r\n";
                    decodedTokens += DecodeToken(_authResponse.AccessToken);
                }

                txtResult.Text = decodedTokens;
            }
        }
        private async Task StartFlowAsync(string responseType, string scope)
        {
            Exception exception = null;

            try
            {
                _response = await WebAuthentication.DoImplicitFlowAsync(
                    new Uri(Constants.AuthorizeEndpoint),
                    "implicitclient",
                    responseType,
                    scope);

                Output.Text = _response.Raw;
                ParseResponse();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                var md = new MessageDialog(exception.ToString());
                await md.ShowAsync();
            }
        }
Example #3
0
        public async Task signout_callback_with_mismatched_id_token_hint_should_not_pass_along_logout_message()
        {
            await _mockPipeline.LoginAsync("bob");

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");

            _mockPipeline.BrowserClient.AllowAutoRedirect = false;
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            var id_token      = authorization.IdentityToken;

            await _mockPipeline.LoginAsync("alice");

            _mockPipeline.BrowserClient.AllowAutoRedirect = true;
            response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint +
                                                                  "?id_token_hint=" + id_token +
                                                                  "&post_logout_redirect_uri=https://client1/signout-callback");

            _mockPipeline.LogoutRequest.ClientId.Should().BeNull();
            _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull();
        }
Example #4
0
        public async Task login_response_and_consent_response_should_receive_authorization_response()
        {
            _mockPipeline.Subject        = IdentityServerPrincipal.Create("bob", "Bob Loblaw");
            _mockPipeline.SignInResponse = new SignInResponse();

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesConsented = new string[] { "openid", "api1", "profile" }
            };

            _browser.StopRedirectingAfter = 4;

            var url = CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _client.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
            var scopes = authorization.Scope.Split(' ');

            scopes.ShouldAllBeEquivalentTo(new string[] { "profile", "api1", "openid" });
        }
Example #5
0
        public async Task consent_response_should_allow_successful_authorization_response()
        {
            await _mockPipeline.LoginAsync("bob");

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesConsented = new string[] { "openid", "api2" }
            };
            _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
            var scopes = authorization.Scope.Split(' ');

            scopes.ShouldAllBeEquivalentTo(new string[] { "api2", "openid" });
        }
        private void webView_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(_callbackUri.AbsoluteUri))
            {
                if (e.Uri.AbsoluteUri.Contains("#"))
                {
                    AuthorizeResponse = new AuthorizeResponse(e.Uri.AbsoluteUri);
                }
                else
                {
                    var document = (IHTMLDocument3)((WebBrowser)sender).Document;
                    var inputElements = document.getElementsByTagName("INPUT").OfType<IHTMLElement>();
                    var resultUrl = "?";

                    foreach (var input in inputElements)
                    {
                        resultUrl += input.getAttribute("name") + "=";
                        resultUrl += input.getAttribute("value") + "&";
                    }

                    resultUrl = resultUrl.TrimEnd('&');
                    AuthorizeResponse = new AuthorizeResponse(resultUrl);
                }

                e.Cancel = true;
                this.Visibility = Visibility.Hidden;

                if (Done != null)
                {
                    Done.Invoke(this, AuthorizeResponse);
                }
            }
        }
Example #7
0
        public async Task consent_response_missing_required_scopes_should_error()
        {
            await _mockPipeline.LoginAsync("bob");

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesValuesConsented = new string[] { "api2" }
            };
            _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeTrue();
            authorization.Error.Should().Be("access_denied");
            authorization.State.Should().Be("123_state");
        }
    public async Task Request_with_response_type_code_supported()
    {
        await _mockPipeline.LoginAsync("bob");

        var metadata = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryEndpoint);

        metadata.StatusCode.Should().Be(HttpStatusCode.OK);

        var state = Guid.NewGuid().ToString();
        var nonce = Guid.NewGuid().ToString();

        var url = _mockPipeline.CreateAuthorizeUrl(
            clientId: "code_client",
            responseType: "code",
            scope: "openid",
            redirectUri: "https://code_client/callback",
            state: state,
            nonce: nonce);
        var response = await _mockPipeline.BrowserClient.GetAsync(url);

        response.StatusCode.Should().Be(HttpStatusCode.Found);

        var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

        authorization.IsError.Should().BeFalse();
        authorization.Code.Should().NotBeNull();
        authorization.State.Should().Be(state);
    }
Example #9
0
        public async Task get_request_should_redirect_to_configured_logout_path()
        {
            _mockPipeline.Options.UserInteraction.LogoutUrl         = "/logout";
            _mockPipeline.Options.UserInteraction.LogoutIdParameter = "id";

            await _mockPipeline.LoginAsync("bob");

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");

            _mockPipeline.BrowserClient.AllowAutoRedirect = false;
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            var id_token      = authorization.IdentityToken;

            response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint +
                                                                  "?id_token_hint=" + id_token +
                                                                  "&post_logout_redirect_uri=https://client1/signout-callback");

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://server/logout?id=");
        }
        private void webView_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(_callbackUri.AbsoluteUri))
            {
                AuthorizeResponse = new AuthorizeResponse(e.Uri.AbsoluteUri);

                e.Cancel = true;
                this.Visibility = System.Windows.Visibility.Hidden;
                
                if (Done != null)
                {
                    Done.Invoke(this, AuthorizeResponse);
                }
            }
        }
    public async Task Restricted_implicit_client_can_request_IdToken()
    {
        await _mockPipeline.LoginAsync(_user);

        var url = _mockPipeline.CreateAuthorizeUrl("client2",
                                                   "id_token", "openid", "https://client2/callback", "state", "nonce");

        _mockPipeline.BrowserClient.AllowAutoRedirect = false;
        var response = await _mockPipeline.BrowserClient.GetAsync(url);

        response.StatusCode.Should().Be(HttpStatusCode.Found);
        response.Headers.Location.AbsoluteUri.Should().StartWith("https://client2/callback");
        var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

        authorization.IdentityToken.Should().NotBeNull();
        authorization.AccessToken.Should().BeNull();
    }
Example #12
0
        public async Task login_response_and_consent_response_should_receive_authorization_response(Type storeType)
        {
            if (storeType != null)
            {
                _mockPipeline.OnPostConfigureServices += services =>
                {
                    services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
                };
                _mockPipeline.Initialize();
            }

            _mockPipeline.Subject = new IdentityServerUser("bob").CreatePrincipal();

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesValuesConsented = new string[] { "openid", "api1", "profile" }
            };

            _mockPipeline.BrowserClient.StopRedirectingAfter = 4;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
            var scopes = authorization.Scope.Split(' ');

            scopes.Should().BeEquivalentTo(new string[] { "profile", "api1", "openid" });
        }
Example #13
0
    public async Task signout_should_support_POST()
    {
        await _mockPipeline.LoginAsync("bob");

        var url = _mockPipeline.CreateAuthorizeUrl(
            clientId: "client1",
            responseType: "id_token",
            scope: "openid",
            redirectUri: "https://client1/callback",
            state: "123_state",
            nonce: "123_nonce");

        _mockPipeline.BrowserClient.AllowAutoRedirect = false;
        var response = await _mockPipeline.BrowserClient.GetAsync(url);

        var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
        var id_token      = authorization.IdentityToken;

        _mockPipeline.BrowserClient.AllowAutoRedirect = true;

        var values = new List <KeyValuePair <string, string> >();

        values.Add(new KeyValuePair <string, string>("id_token_hint", id_token));
        values.Add(new KeyValuePair <string, string>("post_logout_redirect_uri", "https://client1/signout-callback"));
        var content = new FormUrlEncodedContent(values);

        response = await _mockPipeline.BrowserClient.PostAsync(IdentityServerPipeline.EndSessionEndpoint, content);

        _mockPipeline.LogoutWasCalled.Should().BeTrue();
        _mockPipeline.LogoutRequest.Should().NotBeNull();
        _mockPipeline.LogoutRequest.ClientId.Should().Be("client1");
        _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().Be("https://client1/signout-callback");

        var parts = _mockPipeline.LogoutRequest.SignOutIFrameUrl.Split('?');

        parts[0].Should().Be(IdentityServerPipeline.EndSessionCallbackEndpoint);
        var iframeUrl = QueryHelpers.ParseNullableQuery(parts[1]);

        iframeUrl["endSessionId"].FirstOrDefault().Should().NotBeNull();
    }
Example #14
0
        private async Task LoginUsingUsernameAndPasswordAsync()
        {
            const string responseType = "code id_token"; //implicit flow: "id_token token"

            // Space-separated list of scopes we want to receive
            var scopes = $"openid email profile offline_access {TimesheetConstants.ApiScope}";
            var nonce = GenerateNonce(); // Unique token for the authorization request.

            try
            {
                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
                var request = new AuthorizeRequest(TimesheetConstants.AuthorizeEndpoint);
                var authUrl = request.CreateAuthorizeUrl(TimesheetConstants.ClientId, responseType, scopes, redirectUri.ToString(), nonce: nonce);
                var requestUri = new Uri(authUrl);

                var result =
                    await
                        WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, redirectUri);

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    // Successful authentication, but we only have the ID token. 
                    var response = new AuthorizeResponse(result.ResponseData);

                    // We need to ask for the access token and refresh tokens now.
                    var tokenResponse = await GetAuthTokenAsync(response);

                    // Store the tokens in the password vault
                    ApiService.StoreTokenInVault(tokenResponse);
                    
                    // And finish the login process
                    await FinishLoginAsync(tokenResponse);
                }
            }
            catch (Exception ex)
            {
                var dlg = new MessageDialog(ex.Message, "Error");
                await dlg.ShowAsync();
            }
        }
Example #15
0
    public async Task consent_response_of_temporarily_unavailable_should_return_error_to_client(Type storeType)
    {
        if (storeType != null)
        {
            _mockPipeline.OnPostConfigureServices += services =>
            {
                services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
            };
            _mockPipeline.Initialize();
        }

        await _mockPipeline.LoginAsync("bob");

        _mockPipeline.ConsentResponse = new ConsentResponse()
        {
            Error            = AuthorizationError.TemporarilyUnavailable,
            ErrorDescription = "some description"
        };
        _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

        var url = _mockPipeline.CreateAuthorizeUrl(
            clientId: "client2",
            responseType: "id_token token",
            scope: "openid profile api1 api2",
            redirectUri: "https://client2/callback",
            state: "123_state",
            nonce: "123_nonce");
        var response = await _mockPipeline.BrowserClient.GetAsync(url);

        response.StatusCode.Should().Be(HttpStatusCode.Redirect);
        response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

        var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

        authorization.IsError.Should().BeTrue();
        authorization.Error.Should().Be("temporarily_unavailable");
        authorization.ErrorDescription.Should().Be("some description");
    }
Example #16
0
    public async Task valid_id_token_hint_but_no_post_logout_redirect_uri_should_not_use_any_of_multiple_registered_post_logout_redirect_uri()
    {
        await _mockPipeline.LoginAsync("bob");

        _mockPipeline.BrowserClient.AllowAutoRedirect = false;
        var url = _mockPipeline.CreateAuthorizeUrl(
            clientId: "client2",
            responseType: "id_token",
            scope: "openid",
            redirectUri: "https://client2/callback",
            state: "123_state",
            nonce: "123_nonce");
        var response = await _mockPipeline.BrowserClient.GetAsync(url);

        var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
        var id_token      = authorization.IdentityToken;

        _mockPipeline.BrowserClient.AllowAutoRedirect = true;
        response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint +
                                                              "?id_token_hint=" + id_token);

        _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull();
    }
Example #17
0
        public async Task signin_response_should_allow_successful_authorization_response()
        {
            _mockPipeline.Subject = new IdentityServerUser("bob").CreatePrincipal();
            _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client1/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
        }
Example #18
0
        public async Task authenticated_user_with_valid_request_should_receive_authorization_response()
        {
            await _mockPipeline.LoginAsync("bob");

            _mockPipeline.BrowserClient.AllowAutoRedirect = false;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client1/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());

            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
        }
        private Task<AuthorizeResult> ParseResponse(string webViewResponse, AuthorizeResult result)
        {
            var response = new AuthorizeResponse(webViewResponse);

            if (response.IsError)
            {
                result.Error = response.Error;
                return Task.FromResult(result);
            }

            if (string.IsNullOrEmpty(response.Code))
            {
                result.Error = "Missing authorization code";
                return Task.FromResult(result);
            }

            if (string.IsNullOrEmpty(response.IdentityToken))
            {
                result.Error = "Missing identity token";
                return Task.FromResult(result);
            }

            result.IdentityToken = response.IdentityToken;
            result.Code = response.Code;
            result.IsError = false;

            return Task.FromResult(result);
        }
        public async Task login_response_and_consent_response_should_receive_authorization_response()
        {
            _mockPipeline.Subject = IdentityServerPrincipal.Create("bob", "Bob Loblaw");
            _mockPipeline.SignInResponse = new SignInResponse();

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesConsented = new string[] { "openid", "api1", "profile" }
            };

            _mockPipeline.BrowserClient.StopRedirectingAfter = 4;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
            var scopes = authorization.Scope.Split(' ');
            scopes.ShouldAllBeEquivalentTo(new string[] { "profile", "api1", "openid" });
        }
        public async Task consent_response_missing_required_scopes_should_error()
        {
            await _mockPipeline.LoginAsync("bob");

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesConsented = new string[] { "api2" }
            };
            _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);
            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            authorization.IsError.Should().BeTrue();
            authorization.Error.Should().Be("access_denied");
            authorization.State.Should().Be("123_state");
        }
        public async Task authenticated_user_with_valid_request_should_receive_authorization_response()
        {
            await _mockPipeline.LoginAsync("bob");

            _mockPipeline.BrowserClient.AllowAutoRedirect = false;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client1/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
        }
        public async Task signin_response_should_allow_successful_authorization_response()
        {
            _mockPipeline.Subject = IdentityServerPrincipal.Create("bob", "Bob Loblaw");
            _mockPipeline.SignInResponse = new SignInResponse();
            _mockPipeline.BrowserClient.StopRedirectingAfter = 2;

            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: "client1",
                responseType: "id_token",
                scope: "openid",
                redirectUri: "https://client1/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client1/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
        }
 private async void _login_Done(object sender, AuthorizeResponse e)
 {
     _result = await ValidateResponseAsync(e);
     ShowTokenResult();
 }
        private async Task<LoginResult> ValidateResponseAsync(AuthorizeResponse response)
        {
            // id_token validieren
            var tokenClaims = ValidateIdentityToken(response.IdentityToken);

            if (tokenClaims == null)
            {
                return new LoginResult { ErrorMessage = "Invalid identity token." };
            }

            // nonce validieren
            var nonce = tokenClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.Nonce);

            if (nonce == null || !string.Equals(nonce.Value, _nonce, StringComparison.Ordinal))
            {
                return new LoginResult { ErrorMessage = "Inalid nonce." };
            }

            // c_hash validieren
            var c_hash = tokenClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthorizationCodeHash);

            if (c_hash == null || ValidateCodeHash(c_hash.Value, response.Code) == false)
            {
                return new LoginResult { ErrorMessage = "Invalid code." };
            }

            _provider = JwkNetExtensions.CreateProvider();
            var jwk = _provider.ToJsonWebKey();

            // code eintauschen gegen tokens
            var tokenClient = new TokenClient(
                _config.TokenEndpoint,
                _settings.ClientId,
                _settings.ClientSecret);

            var tokenResponse = await tokenClient.RequestAuthorizationCodePopAsync(
                code: response.Code,
                redirectUri: _settings.RedirectUri,
                codeVerifier: _verifier,
                algorithm: jwk.Alg,
                key: jwk.ToJwkString());

            if (tokenResponse.IsError)
            {
                return new LoginResult { ErrorMessage = tokenResponse.Error };
            }

            // optional userinfo aufrufen
            var profileClaims = new List<Claim>();
            if (_settings.LoadUserProfile)
            {
                var userInfoClient = new UserInfoClient(
                    new Uri(_config.UserInfoEndpoint),
                    tokenResponse.AccessToken);

                var userInfoResponse = await userInfoClient.GetAsync();
                profileClaims = userInfoResponse.GetClaimsIdentity().Claims.ToList();
            }

            var principal = CreatePrincipal(tokenClaims, profileClaims);

            return new LoginResult
            {
                Success = true,
                User = principal,
                IdentityToken = response.IdentityToken,
                AccessToken = tokenResponse.AccessToken,
                RefreshToken = tokenResponse.RefreshToken,
                AccessTokenExpiration = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn)
            };
        }
Example #26
0
        private async System.Threading.Tasks.Task<TokenResponse> GetAuthTokenAsync(AuthorizeResponse response)
        {
            var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            // Let's get the actual (short lived) access token using the authorization code.
            var tokenClient = new TokenClient(
                            TimesheetConstants.TokenEndpoint,
                            TimesheetConstants.ClientId,
                            "mysupersecretkey");

            return await tokenClient.RequestAuthorizationCodeAsync(response.Code, redirectUri.ToString());
        }
 void _login_Done(object sender, AuthorizeResponse e)
 {
     _response = e;
     Textbox1.Text = e.Raw;
 }
        private async void webView_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            AuthorizeResponse response;

            if (e.Uri.ToString().StartsWith(_settings.RedirectUri))
            {
                if (e.Uri.AbsoluteUri.Contains("#"))
                {
                    response = new AuthorizeResponse(e.Uri.AbsoluteUri);
                }
                // form_post support
                else
                {
                    var document = (IHTMLDocument3)((WebBrowser)sender).Document;
                    var inputElements = document.getElementsByTagName("INPUT").OfType<IHTMLElement>();
                    var resultUrl = "?";

                    foreach (var input in inputElements)
                    {
                        resultUrl += input.getAttribute("name") + "=";
                        resultUrl += input.getAttribute("value") + "&";
                    }

                    resultUrl = resultUrl.TrimEnd('&');
                    response = new AuthorizeResponse(resultUrl);
                }

                e.Cancel = true;
                this.Visibility = Visibility.Hidden;

                var loginResult = await ValidateResponseAsync(response);
                Done?.Invoke(this, loginResult);
            }
        }
Example #29
0
        public async Task consent_response_should_allow_successful_authorization_response()
        {
            await LoginAsync("bob");

            _mockPipeline.ConsentResponse = new ConsentResponse()
            {
                ScopesConsented = new string[] { "openid", "api2" }
            };
            _browser.StopRedirectingAfter = 2;

            var url = CreateAuthorizeUrl(
                clientId: "client2",
                responseType: "id_token token",
                scope: "openid profile api1 api2",
                redirectUri: "https://client2/callback",
                state: "123_state",
                nonce: "123_nonce");
            var response = await _client.GetAsync(url);

            response.StatusCode.Should().Be(HttpStatusCode.Redirect);
            response.Headers.Location.ToString().Should().StartWith("https://client2/callback");

            var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
            authorization.IsError.Should().BeFalse();
            authorization.IdentityToken.Should().NotBeNull();
            authorization.State.Should().Be("123_state");
            var scopes = authorization.Scope.Split(' ');
            scopes.ShouldAllBeEquivalentTo(new string[] { "api2", "openid" });
        }