static async Task <string> RequestTokenAsync() { var webView = new LoopbackWebView(callbackPort, callbackPath); var loggerFactory = new LoggerFactory(); // uncomment this line for logging inside OidcClient //loggerFactory.AddSerilog(Log.Logger); var opts = new OidcClientOptions(authority, scope, callbackBase + callbackPort + callbackPath, clientId, webView: webView, loggerFactory: loggerFactory) { UseFormPost = true }; var client = new OidcClient(opts); var result = await client.LoginAsync(); if (!result.Success) { Console.WriteLine($"Error: {result.Error}."); return(null); } Console.WriteLine($"Access token: {result.AccessToken}"); return(result.AccessToken); }
private static async Task Login() { // create a redirect URI using an available port on the loopback address. // requires the OP to allow random ports on 127.0.0.1 - otherwise set a static port var browser = new SystemBrowser(64879); string redirectUri = string.Format($"http://127.0.0.1:{browser.Port}"); var options = new OidcClientOptions { Authority = _authority, ClientId = "swaggerui", RedirectUri = redirectUri, Scope = "openid profile IdentityServerApi", FilterClaims = false, Browser = browser, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect }; options.Policy.Discovery.ValidateIssuerName = false; options.BackchannelHandler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = (message, certificate, chain, sslPolicyErrors) => true }; options.LoggerFactory.AddSerilog(serviceProvider.GetService <Serilog.ILogger>()); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(new LoginRequest()); ShowResult(result); await NextSteps(result); }
private async void Login() { var options = new OidcClientOptions() { Authority = "https://localhost:5001/", ClientId = "MeetingsWpfApplication", Scope = "openid profile", RedirectUri = "http://127.0.0.1/sample-wpf-app", Browser = new WpfEmbeddedBrowser() }; _oidcClient = new OidcClient(options); LoginResult result; try { result = await _oidcClient.LoginAsync(); } catch (Exception ex) { Message = $"Unexpected Error: {ex.Message}"; return; } if (result.IsError) { Message = result.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : result.Error; } else { var name = result.User.Identity.Name; Message = $"Hello {name}"; } }
private static async Task Login() { var browser = new SystemBrowser(45656); string redirectUri = "https://127.0.0.1:45656"; var options = new OidcClientOptions { Authority = _authority, ClientId = "native.code", RedirectUri = redirectUri, Scope = "openid profile native_api", FilterClaims = false, Browser = browser, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, LoadProfile = true }; var serilog = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}") .CreateLogger(); options.LoggerFactory.AddSerilog(serilog); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(new LoginRequest()); ShowResult(result); await NextSteps(result); }
private static async Task SignIn() { // create a redirect URI using an available port on the loopback address. string redirectUri = string.Format("http://127.0.0.1:7890/"); var options = new OidcClientOptions { Authority = Constants.Authority, ClientId = "console.hybrid.pkce", RedirectUri = redirectUri, Scope = "openid profile api1", FilterClaims = false, Browser = new SystemBrowser(port: 7890) }; var serilog = new LoggerConfiguration() .MinimumLevel.Error() .Enrich.FromLogContext() .WriteTo.LiterateConsole(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}") .CreateLogger(); options.LoggerFactory.AddSerilog(serilog); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(); ShowResult(result); await NextSteps(result); }
/// <summary> /// The entry point of the application /// </summary> /// <param name="args">The CLI arguments</param> public static async Task Main(string[] args) { var network = new NetworkService(); var browser = new SystemBrowser(network.GetNextAvailablePort()); var redirectUri = $"http://127.0.0.1:{browser.Port}"; var options = new OidcClientOptions { Authority = "https://localhost:11009", ClientId = "native", RedirectUri = redirectUri, Browser = browser, Scope = "openid profile email", FilterClaims = false }; var client = new OidcClient(options); var result = await client.LoginAsync(new LoginRequest { BrowserTimeout = (int)TimeSpan.FromMinutes(5).TotalSeconds, BrowserDisplayMode = DisplayMode.Visible }); if (result.IsError) { Console.WriteLine($"Error while logging in {result.Error}"); return; } Console.WriteLine($"Got token {result.AccessToken}"); Console.WriteLine("Hello World!"); }
public async Task <bool> LoginAsync() { var callbackUri = this.appSettingsManager["Authorization:LoginCallback"]; var options = new OidcClientOptions { Authority = $"https://{this.domain}", ClientId = this.clientId, Scope = "openid profile email", RedirectUri = callbackUri, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, Browser = new Browser() }; var oidcClient = new OidcClient(options); var result = await oidcClient.LoginAsync(); if (result.IsError) { throw new AuthenticationException(result.Error); } return(true); }
private async Task login() { if (!allowLogin) { return; } _apiClient = null; initializeOidcClient(); var result = await _oidcClient.LoginAsync(); loginSucceeded = !result.IsError; if (!result.IsError) { currentAccessToken = result.AccessToken; currentIdentityToken = result.IdentityToken; currentRefreshToken = result.RefreshToken; txtCallResult.Text = ""; foreach (Claim claim in result.User.Claims) { //txtCallResult.Text += claim.ToString() + "\n\r"; txtCallResult.Text += claim.ToString() + Environment.NewLine; } } else { MessageBox.Show(this, result.Error, "Login", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async void _loginButton_Click(object sender, System.EventArgs e) { var authority = "https://demo.identityserver.io"; try { var options = new OidcClientOptions { Authority = authority, ClientId = "native.hybrid", Scope = "openid profile api", RedirectUri = "io.identitymodel.native://callback", ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, Browser = new ChromeCustomTabsBrowser(this) }; var oidcClient = new OidcClient(options); _result = await oidcClient.LoginAsync(); // used to redisplay this app if it's hidden by browser StartActivity(GetType()); } catch (Exception ex) { Log("Exception: " + ex.Message, true); Log(ex.ToString()); } }
private async void _loginButton_Click(object sender, System.EventArgs e) { try { _oidcClient = new OidcClient(_options); LoginRequest request = new LoginRequest() { // Use the comments to connect with external provider at once FrontChannelExtraParameters = new Dictionary <string, string>() { //{"acr_values", "idp:Google tenant:Admin"} //{"acr_values", "idp:Google"}, //{"login_hint", "*****@*****.**" } } }; _result = await _oidcClient.LoginAsync(request); _accessToken = _result.AccessToken; _refreshToken = _result.RefreshToken; _identityToken = _result.IdentityToken; // used to redisplay this app if it's hidden by browser StartActivity(GetType()); } catch (Exception ex) { Log("Exception: " + ex.Message, true); Log(ex.ToString()); } }
private async void LoginView_Loaded(object sender, RoutedEventArgs e) { string redirectUri = string.Format("http://127.0.0.1:7890/"); var options = new OidcClientOptions { Authority = _authority, ClientId = "native.hybrid", RedirectUri = redirectUri, Scope = "openid profile api1 email", FilterClaims = false, Browser = _browser }; _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(); if (!result.IsError) { Properties.Settings.Default.AuthCode = result.AccessToken; Properties.Settings.Default.Save(); } else { Properties.Settings.Default.AuthCode = ""; Properties.Settings.Default.Save(); MessageBox.Show(result.Error); } DialogHost.CloseDialogCommand.Execute(null, null); }
private async void LoginView_Loaded(object sender, RoutedEventArgs e) { string redirectUri = string.Format("http://127.0.0.1:7890/"); var options = new OidcClientOptions { Authority = _authority, ClientId = "native.hybrid", RedirectUri = redirectUri, Scope = "openid profile api1 email", FilterClaims = false, Browser = _browser, Policy = new Policy { Discovery = new DiscoveryPolicy { RequireHttps = false } } }; _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(); LoginFinished(this, result); }
private async void buttonNeo4j_Click(object sender, RoutedEventArgs e) { output("redirect URI: " + RedirectUri); // create an HttpListener to listen for requests on that redirect URI. CurrentResult = await OidcClient.LoginAsync(); if (CurrentResult.IsError) { output($"\n\nError:\n{CurrentResult.Error}"); } else { output("\n\nClaims:"); foreach (var claim in CurrentResult.User.Claims) { output($"{claim.Type}: {claim.Value}"); } output(""); output($"Access token:\n{CurrentResult.AccessToken}"); if (!string.IsNullOrWhiteSpace(CurrentResult.RefreshToken)) { output($"Refresh token:\n{CurrentResult.RefreshToken}"); } } }
public static void Main2(string[] args) { var browser = new SystemBrowser(45656); string redirectUri = "http://127.0.0.1:45656"; var options = new OidcClientOptions { Authority = "https://localhost:44370", ClientId = "oidcMVCApp", ClientSecret = "ProCodeGuide", RedirectUri = redirectUri, Scope = "weatherApi.read openid profile", FilterClaims = false, Browser = browser, //IdentityTokenValidator = new JwtHandlerIdentityTokenValidator(), //RefreshTokenInnerHttpHandler = new HttpClientHandler() //Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, //ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, LoadProfile = true }; var _oidcClient = new OidcClient(options); var result = _oidcClient.LoginAsync(new LoginRequest()).Result; Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(result.AccessToken)); }
public string InitAuthorizationCodeGrant() { var clientOptions = LoadOpenIdOptions(); var browser = browserFactory.Browser.WebBrowser; clientOptions.Browser = browser; var oidcClient = new OidcClient(clientOptions); var discoClient = new DiscoveryClient(configurations.HelseIdEndpoint); var discoveryResponse = discoClient.GetAsync(); var disco = discoveryResponse.GetAwaiter().GetResult(); if (disco.IsError) { throw new ArgumentException(disco.Error); } var result = oidcClient.LoginAsync(new LoginRequest() { BackChannelExtraParameters = GetBackChannelExtraParameters(disco, clientOptions.ClientId, configurations.HelseIdCertificateThumbprint, null, JwtGenerator.SigningMethod.X509EnterpriseSecurityKey), // Set idporten as default provider //FrontChannelExtraParameters = new { acr_values = "idp:idporten-oidc Level4", prompt = "Login" } }); var res = result.GetAwaiter().GetResult(); if (res.IsError) { throw new ArgumentException(res.Error); } IsAuthenticated = true; return(AccessToken = res?.AccessToken); }
private static async Task Login() { var browser = new Browser(44377); string redirectUri = "https://localhost:44377/desktop-callback/"; var options = new OidcClientOptions { Authority = "https://sod.superoffice.com/login", LoadProfile = false, ClientId = "", ClientSecret = "", Scope = "openid", RedirectUri = redirectUri, ResponseMode = OidcClientOptions.AuthorizeResponseMode.FormPost, Flow = OidcClientOptions.AuthenticationFlow.Hybrid, Browser = browser }; options.Policy.Discovery.ValidateIssuerName = false; options.Policy.RequireAccessTokenHash = false; var client = new OidcClient(options); var state = await client.PrepareLoginAsync(); Console.WriteLine($"Please wait while login..."); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(new LoginRequest()); if (!result.IsError) { GetTokens(result); } //LoginResult }
private async void OnSignInCommand() { const string accesstokenkey = "AccessToken"; var token = await SecureStorage.GetAsync(accesstokenkey); if (String.IsNullOrEmpty(token)) { var client = new OidcClient(options); var result = await client.LoginAsync(new LoginRequest { BrowserDisplayMode = DisplayMode.Visible }); if (result.IsError) { return; } token = result.AccessToken; //result.RefreshToken //result.User await SecureStorage.SetAsync(accesstokenkey, token); await SecureStorage.SetAsync("RefreshToken", result.RefreshToken); } apiClient.SetBearerToken(token); await NavigationService.NavigateAsync("nav/main"); }
/// <summary> /// 登录。 /// </summary> /// <returns>服务结果。</returns> public async Task <ServiceResult> LoginAsync() { var oidcClient = new OidcClient(CreateOidcClientOptions()); LoginResult loginResult = null; try { loginResult = await oidcClient.LoginAsync(new LoginRequest()); } catch (Exception e) { return(new ServiceResult { Status = ServiceResultStatus.Exception, Message = e.Message }); } if (!string.IsNullOrEmpty(loginResult.Error)) { return new ServiceResult { Status = ServiceResultStatusHelper.FromHttpStatusCode( HttpStatusCode.BadRequest), Message = loginResult.Error } } ; var refreshTokenHandler = (RefreshTokenHandler)loginResult.RefreshTokenHandler; _refreshToken = refreshTokenHandler.RefreshToken; _accessToken = refreshTokenHandler.AccessToken; return(new ServiceResult { Status = ServiceResultStatus.OK }); }
async void Login_Clicked(object sender, EventArgs e) { var browser = DependencyService.Get <IBrowser>(); var options = new OidcClientOptions { Authority = "https://demo.identityserver.io", ClientId = "native.hybrid", Scope = "openid profile email api offline_access", RedirectUri = "xamarinformsclients://callback", Browser = browser, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect }; client = new OidcClient(options); result = await client.LoginAsync(new LoginRequest()); if (result.IsError) { await DisplayAlert("Access Token", "Login error", "OK"); return; } await DisplayAlert("Access Token", result.AccessToken, "OK"); }
private static async Task SignIn() { // create a redirect URI using an available port on the loopback address. // requires the OP to allow random ports on 127.0.0.1 - otherwise set a static port var browser = new SystemBrowser(); string redirectUri = string.Format($"http://127.0.0.1:{browser.Port}"); var options = new OidcClientOptions { Authority = Authority, ClientId = ClientId, RedirectUri = redirectUri, Scope = $"openid profile {Scope}", FilterClaims = false, Browser = browser, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, }; _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(extraParameters : new { acr_values = $"tenant:{Tenant}" }); ShowResult(result); await NextSteps(result); }
private static async Task <string> LaunchBrowserForTokenAsync() { var browser = new SystemBrowser(12345, "/native_client_callback"); var opts = new OidcClientOptions { Authority = authorityUrl, Scope = "openid movie_api", RedirectUri = "http://127.0.0.1:12345/native_client_callback", ClientId = "native_client", Browser = browser, }; // uncomment this line to enable logging //opts.LoggerFactory.AddConsole(LogLevel.Trace); var client = new OidcClient(opts); var result = await client.LoginAsync(); if (result.IsError) { Console.WriteLine($"Error: {result.Error}."); return(null); } return(result.AccessToken); }
private async void Login_Clicked(object sender, EventArgs e) { _result = await _client.LoginAsync(new LoginRequest()); if (_result.IsError) { OutputText.Text = _result.Error; return; } var sb = new StringBuilder(128); foreach (var claim in _result.User.Claims) { sb.AppendFormat("{0}: {1}\n", claim.Type, claim.Value); } sb.AppendFormat("\n{0}: {1}\n", "refresh token", _result?.RefreshToken ?? "none"); sb.AppendFormat("\n{0}: {1}\n", "access token", _result.AccessToken); OutputText.Text = sb.ToString(); _apiClient.Value.SetBearerToken(_result?.AccessToken ?? ""); _apiClient.Value.BaseAddress = new Uri("https://as.landsense.eu"); }
public async void DisplayDonationAsync() { var httpClient = new HttpClient(); var accessToken = await SecureStorage.GetAsync(Constants.AccessToken) ?? throw new Exception("Access token not found"); if (accessToken == null) { _result = await client.LoginAsync(new LoginRequest()); if (_result.IsError) { ErrorMessage = _result.Error; return; } accessToken = _result.AccessToken; await SecureStorage.SetAsync(Constants.AccessToken, accessToken); } if (httpClient.DefaultRequestHeaders.Authorization == null) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } var uri = new Uri($"{current}/api/Admin/donation/{eventId}"); var donations = await httpClient.GetFromJsonAsync <IEnumerable <DtoDonation> >(uri); foreach (var donation in donations) { Donations.Add(donation); Console.WriteLine(Donations.Count); } }
public async Task <ClaimsPrincipal> SignIn() { // create a redirect URI using an available port on the loopback address. // requires the OP to allow random ports on 127.0.0.1 - otherwise set a static port var browser = new Browser(12345); string redirectUri = string.Format($"http://localhost:{browser.Port}/"); var options = new OidcClientOptions { Authority = System.Configuration.ConfigurationManager.AppSettings["SSO"], ClientId = System.Configuration.ConfigurationManager.AppSettings["SSO.Client"], ClientSecret = System.Configuration.ConfigurationManager.AppSettings["SSO.Secret"], RedirectUri = redirectUri, Scope = "openid profile", FilterClaims = false, Browser = browser }; _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(new LoginRequest()); if (result.IsError) { Console.WriteLine("\n\nError:\n{0}", result.Error); return(null); } return(result.User); }
public async void Start(object sender, RoutedEventArgs e) { var options = new OidcClientOptions() { Authority = "https://demo.identityserver.io/", ClientId = "interactive.public", Scope = "openid profile email", RedirectUri = "http://127.0.0.1/sample-wpf-app", Browser = new WpfEmbeddedBrowser() }; _oidcClient = new OidcClient(options); LoginResult result; try { result = await _oidcClient.LoginAsync(); } catch (Exception ex) { Message.Text = $"Unexpected Error: {ex.Message}"; return; } if (result.IsError) { Message.Text = result.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : result.Error; } else { var name = result.User.Identity.Name; Message.Text = $"Hello {name}"; } }
private async void LoginButton_Click(object sender, EventArgs e) { AccessTokenDisplay.Clear(); OtherDataDisplay.Clear(); var result = await _oidcClient.LoginAsync(DisplayMode.Visible); if (result.IsError) { MessageBox.Show(this, result.Error, "Login", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { AccessTokenDisplay.Text = result.AccessToken; var sb = new StringBuilder(128); foreach (var claim in result.User.Claims) { sb.AppendLine($"{claim.Type}: {claim.Value}"); } if (!string.IsNullOrWhiteSpace(result.RefreshToken)) { sb.AppendLine($"refresh token: {result.RefreshToken}"); } OtherDataDisplay.Text = sb.ToString(); _apiClient = new HttpClient(result.RefreshTokenHandler); _apiClient.BaseAddress = new Uri("https://api.identityserver.io/"); } }
public static async Task <LoginResult> Start(IBrowser browser) { //Do not use this in production environment. var handler = HttpClientExtensions.CreateHttpClientHandler(true); var options = new OidcClientOptions { Authority = Config.IdentityServerUrl, BackchannelHandler = handler, Browser = browser, ClientId = "NativeClient", ClientSecret = "KHG+TZ8aaVx2h3^!vJ65", FilterClaims = false, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode, LoadProfile = true, Scope = "openid profile Api1 Cluster", RedirectUri = Config.NativeClientUrl, RefreshTokenInnerHttpHandler = handler, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect }; var client = new OidcClient(options); return(await client.LoginAsync(new LoginRequest())); }
private static async Task SignIn() { // create a redirect URI using an available port on the loopback address. // requires the OP to allow random ports on 127.0.0.1 - otherwise set a static port var browser = new SystemBrowser(); string redirectUri = string.Format($"http://127.0.0.1:{browser.Port}"); var options = new OidcClientOptions { Authority = Constants.Authority, ClientId = "console.pkce", RedirectUri = redirectUri, Scope = "openid profile feature1", FilterClaims = false, Browser = browser }; var serilog = new LoggerConfiguration() .MinimumLevel.Error() .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}") .CreateLogger(); options.LoggerFactory.AddSerilog(serilog); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(new LoginRequest()); ShowResult(result); await NextSteps(result); }
private async void Login_Clicked(object sender, EventArgs e) { _result = await _client.LoginAsync(new LoginRequest()); if (_result.IsError) { OutputText.Text = _result.Error; return; } var sb = new StringBuilder(128); foreach (var claim in _result.User.Claims) { sb.AppendFormat("{0}: {1}\n", claim.Type, claim.Value); } sb.AppendFormat("\n{0}: {1}\n", "refresh token", _result?.RefreshToken ?? "none"); sb.AppendFormat("\n{0}: {1}\n", "access token", _result.AccessToken); OutputText.Text = sb.ToString(); _apiClient.Value.SetBearerToken(_result?.AccessToken ?? ""); // 10.0.2.2 is an alias for localhost on the computer when using the android emulator _apiClient.Value.BaseAddress = new Uri("http://10.0.2.2:50405/"); }
private static async Task <LoginResult> Login(OidcClient client) { var request = new LoginRequest(); var result = await client.LoginAsync(request); return(result); }
private async void LoginButton_Click(object sender, RoutedEventArgs e) { var authority = "https://demo.identityserver.io"; var webView = new UwpWebView(enableWindowsAuthentication: false); var options = new OidcClientOptions( authority: authority, clientId: "native", clientSecret: "secret", scope: "openid profile api offline_access", redirectUri: WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri, webView: webView); var client = new OidcClient(options); var result = await client.LoginAsync(); if (!string.IsNullOrEmpty(result.Error)) { ResultTextBox.Text = result.Error; return; } var sb = new StringBuilder(128); foreach (var claim in result.Claims) { sb.AppendLine($"{claim.Type}: {claim.Value}"); } sb.AppendLine($"refresh token: {result.RefreshToken}"); sb.AppendLine($"access token: {result.AccessToken}"); ResultTextBox.Text = sb.ToString(); _client = new HttpClient(result.Handler); _client.BaseAddress = new Uri("https://demo.identityserver.io/api/"); }