/// <summary>
        /// Handles the auth result.Should be called from <see cref="Activity.OnActivityResult(int, Result, Intent)">
        /// </summary>
        /// <returns>The auth result.</returns>
        /// <param name="intent">Intent.</param>
        public async Task HandleAuthResult(Intent intent)
        {
            NonNull(intent, "intent");
            NonNull(authenticateTaskComplete, "authenticateTaskComplete");

            AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
            AuthorizationException error    = AuthorizationException.FromIntent(intent);

            authState.Update(response, error);

            if (response != null)
            {
                try
                {
                    User user = await exchangeTokens(response);

                    authenticateTaskComplete.TrySetResult(user);
                }
                catch (Exception ex)
                {
                    this.logger.Error("Unexpected error in token exchange", ex);
                    authenticateTaskComplete.TrySetException(ex);
                }
            }
            else
            {
                authenticateTaskComplete.TrySetException(error);
            }
        }
예제 #2
0
        internal void NotifyOfCallback(Intent intent)
        {
            try
            {
                if (!intent.HasExtra(Constants.AuthStateKey))
                {
                    _authState = null;
                }
                else
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(intent.GetStringExtra(Constants.AuthStateKey));
                    }
                    catch (JSONException ex)
                    {
                        Console.WriteLine("Malformed AuthState JSON saved: " + ex);
                        _authState = null;
                    }
                }
                if (_authState != null)
                {
                    AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
                    AuthorizationException authEx   = AuthorizationException.FromIntent(intent);
                    _authState.Update(response, authEx);

                    if (response != null)
                    {
                        Console.WriteLine("Received AuthorizationResponse.");
                        try
                        {
                            var clientAuthentication = _authState.ClientAuthentication;
                        }
                        catch (ClientAuthenticationUnsupportedAuthenticationMethod ex)
                        {
                            _loginResultWaitHandle.Set();

                            Console.WriteLine(
                                "Token request cannot be made, client authentication for the token endpoint could not be constructed: " +
                                ex);

                            return;
                        }
                        _authService.PerformTokenRequest(response.CreateTokenExchangeRequest(), ReceivedTokenResponse);
                    }
                    else
                    {
                        Console.WriteLine("Authorization failed: " + authEx);
                    }
                }
                else
                {
                    _loginResultWaitHandle.Set();
                }
            }
            catch (Exception)
            {
                _loginResultWaitHandle.Set();
            }
        }
예제 #3
0
        protected async void OnSigninButtonClicked(object sender, EventArgs e)
        {
            if (authState.IsAuthorized)
            {
                ResultLabel.Text = StringResources.MsgAlreadyAuthed;
                return;
            }

            try {
                var result = await authState.Client.LoginAsync(new LoginRequest());

                authState.Update(result);
            } catch (Exception ex) {
                authState.Update(ex);
            }

            if (authState.IsAuthorized)
            {
                #region // Write program to be executed when authorization succeeds.
                ResultLabel.Text = StringResources.MsgAuthOk;
                ShowAuthState();
                #endregion
            }
            else
            {
                #region // Write program to be executed when authorization fails.
                ResultLabel.Text = StringResources.MsgAuthNg;
                ShowAuthState();
                #endregion
            }
        }
예제 #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //SetContentView(Resource.Layout.activity_token);

            _authService = new AuthorizationService(this);

            if (savedInstanceState != null)
            {
                if (savedInstanceState.ContainsKey(KEY_AUTH_STATE))
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(savedInstanceState.GetString(KEY_AUTH_STATE));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Malformed authorization JSON saved: " + ex);
                    }
                }

                if (savedInstanceState.ContainsKey(KEY_USER_INFO))
                {
                    try
                    {
                        _userInfoJson = new JSONObject(savedInstanceState.GetString(KEY_USER_INFO));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to parse saved user info JSON: " + ex);
                    }
                }
            }

            if (_authState == null)
            {
                _authState = GetAuthStateFromIntent(Intent);
                var response = AuthorizationResponse.FromIntent(Intent);
                var ex       = AuthorizationException.FromIntent(Intent);
                _authState.Update(response, ex);

                if (response != null)
                {
                    Console.WriteLine("Received AuthorizationResponse");
                    PerformTokenRequest(response.CreateTokenExchangeRequest());
                }
                else
                {
                    Console.WriteLine("Authorization failed: " + ex);
                }
            }

            //RefreshUi();

            //var contactsViewController = App.GetContactsPage().CreateViewController();
            //NavigationController.PresentViewController(contactsViewController, true, null);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
예제 #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_token);

            if (savedInstanceState != null)
            {
                if (savedInstanceState.ContainsKey(KEY_AUTH_STATE))
                {
                    authState = AuthState.JsonDeserialize(savedInstanceState.GetString(KEY_AUTH_STATE));
                }

                if (savedInstanceState.ContainsKey(KEY_USER_INFO))
                {
                    userInfoJson = new JSONObject(savedInstanceState.GetString(KEY_USER_INFO));
                }
            }

            if (authState == null)
            {
                authState = GetAuthStateFromIntent(Intent);
                AuthorizationResponse  response = AuthorizationResponse.FromIntent(Intent);
                AuthorizationException ex       = AuthorizationException.FromIntent(Intent);
                authState.Update(response, ex);
                if (response != null)
                {
                    PerformTokenRequest(response.CreateTokenExchangeRequest());
                }
            }
        }
예제 #6
0
        private void DoPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState
                                      , CredentialsProvider credsProvider)
        {
            string schemeName = authScheme.GetSchemeName();

            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
            }
            AuthScope   authScope = new AuthScope(host, AuthScope.AnyRealm, schemeName);
            Credentials creds     = credsProvider.GetCredentials(authScope);

            if (creds != null)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("BASIC", authScheme.GetSchemeName()))
                {
                    authState.SetState(AuthProtocolState.Challenged);
                }
                else
                {
                    authState.SetState(AuthProtocolState.Success);
                }
                authState.Update(authScheme, creds);
            }
            else
            {
                this.log.Debug("No credentials for preemptive authentication");
            }
        }
예제 #7
0
        public static async Task <HttpGetJsonResult> HttpGetJsonAsync(string uri, AuthState authState)
        {
            if (!authState.IsAuthorized)
            {
                return(new HttpGetJsonResult {
                    Code = X_HTTP_NEED_REAUTHZ
                });
            }
            if (authState.NeedsTokenRefresh)
            {
                RefreshTokenResult result;
                try {
                    result = await authState.Client.RefreshTokenAsync(authState.RefreshToken);

                    authState.Update(result);
                } catch (Exception e) {
                    result = new RefreshTokenResult {
                        Error = e.Message
                    };
                }
                if (result.IsError)
                {
                    return(new HttpGetJsonResult {
                        Code = authState.IsAuthorized ? X_HTTP_ERROR : X_HTTP_NEED_REAUTHZ,
                        Json = new { error = result.Error }
                    });
                }
            }

            try {
#if true
                // Use custom HttpClientHandler for demonstration. (next 4 lines)
                var handler = new HttpClientHandlerEx();
                handler.BeforeRequestAsyncHooks += LogPage.HttpRequestLoggerAsync;
                handler.AfterResponseAsyncHooks += LogPage.HttpResponseLoggerAsync;
                using (var client = new HttpClient(handler: handler)) {
#else
                // This is normal implementation.
                using (var client = new HttpClient()) {
#endif
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authState.AccessToken);
                    var response = await client.GetAsync(uri);

                    return(new HttpGetJsonResult {
                        Code = response.StatusCode == HttpStatusCode.Unauthorized ? X_HTTP_NEED_REAUTHZ : response.StatusCode,
                        Json = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync())
                    });
                }
            } catch (Exception ex) {
                return(new HttpGetJsonResult {
                    Code = X_HTTP_ERROR,
                    Json = new { error = ex.GetType().Name, error_description = ex.Message }
                });
            }
        }
        public void NotifyCallback(Intent intent)
        {
            if (!intent.TryGetAuthStateFromExtra(out authorizationState))
            {
                taskCompletionSource.SetResult(false);
                return;
            }

            AuthorizationResponse  authorizationResponse  = AuthorizationResponse.FromIntent(intent);
            AuthorizationException authorizationException = AuthorizationException.FromIntent(intent);

            authorizationState.Update(authorizationResponse, authorizationException);

            if (authorizationException != null)
            {
                taskCompletionSource.SetResult(false);
                return;
            }

            authorizationService.PerformTokenRequest(authorizationResponse.CreateTokenExchangeRequest(), ReceivedTokenResponse);
        }
        public async Task Refresh()
        {
            if (RefreshToken == null)
            {
                throw new Exception("CurrentCredentials does not have a refresh token");
            }

            TokenLifecycleManager tlcm          = new TokenLifecycleManager();
            TokenResponse         tokenResponse = await tlcm.RefreshTokenAsync(AuthState.CreateTokenRefreshRequest()).ConfigureAwait(false);

            AuthState.Update(tokenResponse, null);
        }
예제 #10
0
        private async Task <AuthState> PerformRefresh(AuthState authState)
        {
            MicroLogger.LogDebug(nameof(PerformRefresh));

            var request = authState.TokenRefreshRequest();

            try
            {
                var tokenResponse = await AuthorizationService.PerformTokenRequestAsync(request);

                MicroLogger.LogDebug($"Received token response with accessToken: {tokenResponse.AccessToken}");

                authState.Update(tokenResponse, null);
            }
            catch (NSErrorException ex)
            {
                authState.Update(ex.Error);

                MicroLogger.LogError($"Token exchange error: {ex}");
            }
            return(authState);
        }
예제 #11
0
        public async Task <string> GetActiveAccessToken()
        {
            if (AuthState.NeedsTokenRefresh)
            {
                try
                {
                    TokenRequest  request  = AuthState.CreateTokenRefreshRequest();
                    TokenResponse response = await AuthService.PerformTokenRequestAsync(request);

                    AuthState.Update(response, null);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }

            return(AuthState.AccessToken);
        }
예제 #12
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (authState == null)
            {
                authState = GetAuthStateFromIntent(Intent);
                AuthorizationResponse  response = AuthorizationResponse.FromIntent(Intent);
                AuthorizationException ex       = AuthorizationException.FromIntent(Intent);
                authState.Update(response, ex);

                if (response != null)
                {
                    Console.WriteLine("Received AuthorizationResponse.");
                    App.OpenIdService.PerformTokenRequest(authState.JsonSerializeString());
                }
                else
                {
                    Console.WriteLine("Authorization failed: " + ex);
                }
            }

            Finish();
        }
예제 #13
0
        internal void NotifyOfCallback(Intent intent)
        {
            try
            {
                if (!intent.HasExtra("authState"))
                {
                    _authState = null;
                }
                else
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(intent.GetStringExtra("authState"));
                    }
                    catch (JSONException)
                    {
                        _authState = null;
                    }
                }
                if (_authState != null)
                {
                    AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
                    AuthorizationException authEx   = AuthorizationException.FromIntent(intent);
                    _authState.Update(response, authEx);
                    if (response != null)
                    {
                        try
                        {
                            var clientAuthentication = _authState.ClientAuthentication;
                        }
                        catch (ClientAuthenticationUnsupportedAuthenticationMethod)
                        {
                            SetWaitHandle();
                            return;
                        }

                        var request = response.CreateTokenExchangeRequest();
                        using (var httpClient = new HttpClient(GetUnsecuredHandler()))
                        {
                            var jObj = new List <KeyValuePair <string, string> >
                            {
                                new KeyValuePair <string, string>("client_id", request.ClientId),
                                new KeyValuePair <string, string>("code", request.AuthorizationCode),
                                new KeyValuePair <string, string>("code_verifier", request.CodeVerifier),
                                new KeyValuePair <string, string>("grant_type", request.GrantType),
                                new KeyValuePair <string, string>("scope", request.Scope),
                                new KeyValuePair <string, string>("redirect_uri", request.RedirectUri.ToString())
                            };
                            var httpRequest = new HttpRequestMessage
                            {
                                Method     = HttpMethod.Post,
                                RequestUri = new Uri(request.Configuration.TokenEndpoint.ToString()),
                                Content    = new FormUrlEncodedContent(jObj)
                            };
                            var httpResult           = httpClient.SendAsync(httpRequest).Result;
                            var tokenResponseJObject = JObject.Parse(httpResult.Content.ReadAsStringAsync().Result);
                            tokenResponseJObject.Add("request", JObject.Parse(request.JsonSerializeString()));
                            var tokenResponse = TokenResponse.JsonDeserialize(new JSONObject(tokenResponseJObject.ToString()));
                            ReceivedTokenResponse(tokenResponse, null);
                        }
                    }
                }
                else
                {
                    SetWaitHandle();
                }
            }
            catch (Exception)
            {
                SetWaitHandle();
            }
        }
예제 #14
0
 private void ReceivedTokenResponse(TokenResponse tokenResponse, AuthorizationException authException)
 {
     Console.WriteLine("Token request complete");
     AuthState.Update(tokenResponse, authException);
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_token);

            authService = new AuthorizationService(this);

            if (savedInstanceState != null)
            {
                if (savedInstanceState.ContainsKey(KEY_AUTH_STATE))
                {
                    try
                    {
                        authState = AuthState.JsonDeserialize(savedInstanceState.GetString(KEY_AUTH_STATE));
                    }
                    catch (JSONException ex)
                    {
                        Console.WriteLine("Malformed authorization JSON saved: " + ex);
                    }
                }

                if (savedInstanceState.ContainsKey(KEY_USER_INFO))
                {
                    try
                    {
                        userInfoJson = new JSONObject(savedInstanceState.GetString(KEY_USER_INFO));
                    }
                    catch (JSONException ex)
                    {
                        Console.WriteLine("Failed to parse saved user info JSON: " + ex);
                    }
                }
            }

            if (authState == null)
            {
                authState = GetAuthStateFromIntent(Intent);
                AuthorizationResponse  response = AuthorizationResponse.FromIntent(Intent);
                AuthorizationException ex       = AuthorizationException.FromIntent(Intent);
                authState.Update(response, ex);

                if (response != null)
                {
                    Console.WriteLine("Received AuthorizationResponse.");
                    PerformTokenRequest(response.CreateTokenExchangeRequest());
                }
                else
                {
                    Console.WriteLine("Authorization failed: " + ex);
                }
            }

            RefreshUi();

            var refreshTokenButton = FindViewById <Button>(Resource.Id.refresh_token);

            refreshTokenButton.Click += delegate
            {
                PerformTokenRequest(authState.CreateTokenRefreshRequest());
            };

            var viewProfileButton = FindViewById <Button>(Resource.Id.view_profile);

            viewProfileButton.Click += delegate
            {
                Task.Run(() => FetchUserInfo());
            };
        }
예제 #16
0
        public App()
        {
            StringResources.Culture = DependencyService.Get <ILocale>().GetLanguage();

            AuthState              = new AuthState();
            AuthState.UpdateHooks += SaveAuthState;

            var browser = DependencyService.Get <IBrowserEx>(DependencyFetchTarget.NewInstance);

            browser.CustomUrlScheme = CUSTOM_URL_SCHEME;
            browser.RedirectUri     = REDIRECT_URI;

            // Setup for demonstration. (next 2 lines)
            browser.BeforeAuthzRequestHooks += LogPage.AuthzRequestLogger;
            browser.AfterAuthzResponseHooks += LogPage.AuthzResponseLogger;

            var options = new OidcClientOptions {
                Authority = ISSUER_URI,
#if __ANDROID__
                ClientId = CLIENT_ID_ANDROID,
#elif __IOS__
                ClientId = CLIENT_ID_IOS,
#endif
                Scope        = SCOPE,
                RedirectUri  = REDIRECT_URI,
                ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect,
                RefreshDiscoveryDocumentForLogin = false,
                Browser = browser
            };

            // Google Accounts has endpoints provided from www.googleapis.com in addition to accounts.google.com.
            options.Policy.Discovery.AdditionalEndpointBaseAddresses = new[] { "https://www.googleapis.com" };

            // Setup for demonstration. (next 4 lines)
            var handler = new HttpClientHandlerEx();

            handler.BeforeRequestAsyncHooks += LogPage.HttpRequestLoggerAsync;
            handler.AfterResponseAsyncHooks += LogPage.HttpResponseLoggerAsync;
            options.BackchannelHandler       = handler;

            // Setup for debugging. (next 5 lines)
            var serilog = new LoggerConfiguration()
                          .MinimumLevel.Verbose()
                          .WriteTo.Debug()
                          .CreateLogger();

            options.LoggerFactory.AddSerilog(serilog);

            var client = new OidcClient(options);

            AuthState.Update(client);

            var file = IsolatedStorageFile.GetUserStoreForApplication();

            try {
                using (var stream = file.OpenFile(PREFERENCE_FILE_NAME, FileMode.Open)) {
                    using (var reader = new StreamReader(stream)) {
                        var crypto = DependencyService.Get <ICrypto>();
                        AuthState.LoadFromJson(crypto.DecryptString(reader.ReadToEnd()));
                    }
                }
            } catch (FileNotFoundException) { }

            InitializeComponent();
            MainPage = new MasterDetail();
        }
예제 #17
0
        public virtual bool HandleAuthChallenge(HttpHost host, HttpResponse response, AuthenticationStrategy
                                                authStrategy, AuthState authState, HttpContext context)
        {
            try
            {
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug(host.ToHostString() + " requested authentication");
                }
                IDictionary <string, Header> challenges = authStrategy.GetChallenges(host, response
                                                                                     , context);
                if (challenges.IsEmpty())
                {
                    this.log.Debug("Response contains no authentication challenges");
                    return(false);
                }
                AuthScheme authScheme = authState.GetAuthScheme();
                switch (authState.GetState())
                {
                case AuthProtocolState.Failure:
                {
                    return(false);
                }

                case AuthProtocolState.Success:
                {
                    authState.Reset();
                    break;
                }

                case AuthProtocolState.Challenged:
                case AuthProtocolState.Handshake:
                {
                    if (authScheme == null)
                    {
                        this.log.Debug("Auth scheme is null");
                        authStrategy.AuthFailed(host, null, context);
                        authState.Reset();
                        authState.SetState(AuthProtocolState.Failure);
                        return(false);
                    }
                    goto case AuthProtocolState.Unchallenged;
                }

                case AuthProtocolState.Unchallenged:
                {
                    if (authScheme != null)
                    {
                        string id        = authScheme.GetSchemeName();
                        Header challenge = challenges.Get(id.ToLower(CultureInfo.InvariantCulture));
                        if (challenge != null)
                        {
                            this.log.Debug("Authorization challenge processed");
                            authScheme.ProcessChallenge(challenge);
                            if (authScheme.IsComplete())
                            {
                                this.log.Debug("Authentication failed");
                                authStrategy.AuthFailed(host, authState.GetAuthScheme(), context);
                                authState.Reset();
                                authState.SetState(AuthProtocolState.Failure);
                                return(false);
                            }
                            else
                            {
                                authState.SetState(AuthProtocolState.Handshake);
                                return(true);
                            }
                        }
                        else
                        {
                            authState.Reset();
                        }
                    }
                }
                }
                // Retry authentication with a different scheme
                Queue <AuthOption> authOptions = authStrategy.Select(challenges, host, response, context
                                                                     );
                if (authOptions != null && !authOptions.IsEmpty())
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Selected authentication options: " + authOptions);
                    }
                    authState.SetState(AuthProtocolState.Challenged);
                    authState.Update(authOptions);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (MalformedChallengeException ex)
            {
                if (this.log.IsWarnEnabled())
                {
                    this.log.Warn("Malformed challenge: " + ex.Message);
                }
                authState.Reset();
                return(false);
            }
        }
예제 #18
0
        /// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void GenerateAuthResponse(IHttpRequest request, AuthState authState
                                                 , HttpContext context)
        {
            AuthScheme  authScheme = authState.GetAuthScheme();
            Credentials creds      = authState.GetCredentials();

            switch (authState.GetState())
            {
            case AuthProtocolState.Failure:
            {
                return;
            }

            case AuthProtocolState.Success:
            {
                EnsureAuthScheme(authScheme);
                if (authScheme.IsConnectionBased())
                {
                    return;
                }
                break;
            }

            case AuthProtocolState.Challenged:
            {
                Queue <AuthOption> authOptions = authState.GetAuthOptions();
                if (authOptions != null)
                {
                    while (!authOptions.IsEmpty())
                    {
                        AuthOption authOption = authOptions.Remove();
                        authScheme = authOption.GetAuthScheme();
                        creds      = authOption.GetCredentials();
                        authState.Update(authScheme, creds);
                        if (this.log.IsDebugEnabled())
                        {
                            this.log.Debug("Generating response to an authentication challenge using " + authScheme
                                           .GetSchemeName() + " scheme");
                        }
                        try
                        {
                            Header header = DoAuth(authScheme, creds, request, context);
                            request.AddHeader(header);
                            break;
                        }
                        catch (AuthenticationException ex)
                        {
                            if (this.log.IsWarnEnabled())
                            {
                                this.log.Warn(authScheme + " authentication error: " + ex.Message);
                            }
                        }
                    }
                    return;
                }
                else
                {
                    EnsureAuthScheme(authScheme);
                }
            }
            }
            if (authScheme != null)
            {
                try
                {
                    Header header = DoAuth(authScheme, creds, request, context);
                    request.AddHeader(header);
                }
                catch (AuthenticationException ex)
                {
                    if (this.log.IsErrorEnabled())
                    {
                        this.log.Error(authScheme + " authentication error: " + ex.Message);
                    }
                }
            }
        }