public async Task AuthenticateUser() { var state = Guid.NewGuid().ToString(); var nonce = Guid.NewGuid().ToString(); await accessTokenSem.WaitAsync(); try { var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri($"{authorizationUrl}/connect/authorize?client_id={clientId}&scope={scopes} openid offline_access&response_type=code id_token&" + $"redirect_uri={redirectUri}&state={state}&nonce={nonce}"), new Uri(redirectUri)); if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var data = webAuthenticationResult.ResponseData; var parms = new WwwFormUrlDecoder(new Uri(data.Replace("#", "?")).Query); if (state != parms.Where(p => p.Name == "state").Single().Value) { throw new UnauthorizedException("State differs"); } var code = parms.Where(p => p.Name == "code").Single().Value; var client = new System.Net.Http.HttpClient(); var dict = new Dictionary <string, string>(); dict.Add("client_id", clientId); dict.Add("client_secret", clientSecret); dict.Add("grant_type", "authorization_code"); dict.Add("code", code); dict.Add("redirect_uri", redirectUri); var res = await client.PostAsync($"{authorizationUrl}/connect/token", new FormUrlEncodedContent(dict)); if (res.IsSuccessStatusCode) { var str = await res.Content.ReadAsStringAsync(); var token = JsonConvert.DeserializeObject <TokenResponse>(str); var tokens = new StoredTokens() { AccessToken = token.access_token, RefreshToken = token.refresh_token, AccessTokenExpires = DateTime.Now.AddSeconds(token.expires_in) }; await tokenStorage.Store(tokens); } else { throw new UnauthorizedException("Could not redeem refresh token."); } } else { throw new UnauthorizedException("Browser authentication was not successful"); } } finally { accessTokenSem.Release(); } }
private async Task ExecuteLogin() { var authInfo = await _loginProvider.LoginAsync(); if (string.IsNullOrWhiteSpace(authInfo.AccessToken) || !authInfo.IsAuthorized) { await _messageService.Show(Global.Error, Global.AppCannotAuthenticate); } else { await _tokenStorage.Store(authInfo); Device.BeginInvokeOnMainThread(async() => { await Shell.Current.GoToAsync("//notifications"); }); } }