public static void AddScopes(this OAuthOptions options, IConfiguration config) { foreach (var scope in JsonConvert.DeserializeObject <List <string> >(config["Authentication:Google:Scopes"])) { options.Scope.Add(scope); } }
private async Task <Tuple <ProjectResource, Exception> > CheckOAuthAccessTokenAsync(ProjectConfiguration project, ProjectResource resource) { var options = new OAuthOptions { AuthorizationUri = resource.AuthorizationUri, ClientId = resource.ClientId, ClientSecret = resource.ClientSecret, Username = resource.Username, Password = resource.Password, Resource = resource.Resource }; try { var oauthClient = _oauthClientFactory.Create(project); // IOAuthClient does not cache tokens Token token = await oauthClient.GetTokenAsync(options, CancellationToken.None); return(Tuple.Create(resource, _noException)); } catch (Exception e) { return(Tuple.Create(resource, e)); } }
public void readAndSetOauthOptionsFromConfig(string ProviderName, OAuthOptions o) { o.ClaimsIssuer = ProviderName; o.ClientId = Configuration[ProviderName + ":ClientId"]; o.ClientSecret = Configuration[ProviderName + ":ClientSecret"]; o.AuthorizationEndpoint = Configuration[ProviderName + ":AuthorizationEndpoint"]; o.TokenEndpoint = Configuration[ProviderName + ":TokenEndpoint"]; o.UserInformationEndpoint = Configuration[ProviderName + ":UserInformationEndpoint"]; o.CallbackPath = new PathString(Configuration[ProviderName + ":CallbackPath"]); o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, Configuration[ProviderName + ":NameId"]); o.ClaimActions.MapJsonKey(ClaimTypes.Name, Configuration[ProviderName + ":Name"]); o.ClaimActions.MapJsonKey(ClaimTypes.Email, Configuration[ProviderName + ":Email"]); o.Scope.Add("openid"); o.Events = new OAuthEvents { OnCreatingTicket = async context => { var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); using (var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync())) { context.RunClaimActions(user.RootElement); } } }; }
private void OAuth() { OAuthOptions oauthOption = new OAuthOptions(); oauthOption.Version = "1.0"; OAuthUrlOptions authoriseOptions = new OAuthUrlOptions(); authoriseOptions.Url = "https://api.twitter.com/oauth/authorize"; authoriseOptions.Args = new Dictionary("force_login", "true"); oauthOption.Authorize = authoriseOptions; OAuthUrlOptions requestOptions = new OAuthUrlOptions(); requestOptions.Url = "https://api.twitter.com/oauth/request_token"; oauthOption.Request = requestOptions; OAuthUrlOptions accessOptions = new OAuthUrlOptions(); accessOptions.Url = "https://api.twitter.com/oauth/access_token"; oauthOption.Access = accessOptions; oauthOption.CallbackUrl = "http://yourcallbackurl"; oauthOption.ConsumerKey = "chameleon_encryped_consumer_key"; oauthOption.ConsumerSecret = "chameleon_encrypted_consumer_secret"; oauthOption.OnResult = delegate(bool success, Dictionary data) { //do something }; Chameleon.PromptOauth(oauthOption); }
static async Task RunAuthenticateVerificationCodeAsync(AppConfig appConfig) { string clientId = appConfig.ClientId; string clientSecret = appConfig.ClientSecret; string redirectUrl = appConfig.RedirectUrl; string verificationCode = appConfig.VerificationCode; if (verificationCode == null) { Console.WriteLine("No verification code"); return; } var oauthOptions = new OAuthOptions(clientId, clientSecret, redirectUrl); var client = new LaunchpadClient(oauthOptions); var accessTokenSource = await client.AuthenticateVerificationCodeAsync(verificationCode); var refreshToken = accessTokenSource.RefreshToken; Console.WriteLine($"Refresh token = {refreshToken}"); var accessToken = await accessTokenSource.GetAccessTokenAsync(); Console.WriteLine($"Access token = {accessToken}"); }
public async Task <IActionResult> Create(AuthenticationViewModel model) { if (ModelState.IsValid) { OAuthOptions oAuthOptions; if (HandlerHelper.GetProviderName(model.HandlerType) == "Google") { oAuthOptions = new GoogleOptions(); } else { oAuthOptions = new OAuthOptions(); } oAuthOptions.ClientId = model.ClientId; oAuthOptions.ClientSecret = model.ClientSecret; oAuthOptions.CallbackPath = "/signin-" + model.Scheme; await _manager.AddAsync(new SchemeDefinition { Scheme = model.Scheme, DisplayName = model.DisplayName, HandlerType = _manager.ManagedHandlerType.First(t => t.Name == model.HandlerType), Options = oAuthOptions }); return(RedirectToAction("List")); } return(View(model)); }
static async Task RunAuthenticateCookieAsync(AppConfig appConfig) { string clientId = appConfig.ClientId; string clientSecret = appConfig.ClientSecret; string redirectUrl = appConfig.RedirectUrl; string cookie = appConfig.BasecampCookie; string username = appConfig.Username; if (cookie == null) { Console.WriteLine("No basecamp cookie"); return; } var oauthOptions = new OAuthOptions(clientId, clientSecret, redirectUrl); var client = new LaunchpadClient(oauthOptions); var accessTokenSource = await client.AuthenticateCookieAsync(cookie, username); var refreshToken = accessTokenSource.RefreshToken; Console.WriteLine($"Refresh token = {refreshToken}"); var accessToken = await accessTokenSource.GetAccessTokenAsync(); Console.WriteLine($"Access token = {accessToken}"); }
public void Configuration(IAppBuilder app) { //第一步:配置跨域访问 app.UseCors(CorsOptions.AllowAll); app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions); //第二步:使用OAuth密码认证模式 app.UseOAuthAuthorizationServer(OAuthOptions.CreateServerOptions()); //第三步:使用Abp app.UseAbp(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.MapSignalR(); //ENABLE TO USE HANGFIRE dashboard (Requires enabling Hangfire in MyAbpProjectWebModule) //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // Authorization = new[] { new AbpHangfireAuthorizationFilter() } //You can remove this line to disable authorization //}); }
private void SetOAuthOptions(OAuthOptions options) { options.ClientId = Configuration[SecretManagerConstants.BattleNetClientID]; options.ClientSecret = Configuration[SecretManagerConstants.BattleNetClientSecret]; options.CallbackPath = new PathString("/signin-battlenet"); options.AuthorizationEndpoint = "https://eu.battle.net/oauth/authorize"; options.TokenEndpoint = "https://eu.battle.net/oauth/token"; options.UserInformationEndpoint = "https://eu.battle.net/oauth/userinfo"; options.Scope.Add("sc2.profile"); options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "battletag"); options.SaveTokens = true; options.Events = new OAuthEvents { OnCreatingTicket = async context => { await CreateOAuthTicket(context); }, OnRemoteFailure = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Failure.Message); return(Task.FromResult(0)); } }; }
public virtual void Configuration(IAppBuilder app) { app.UseAbp(); //配置跨域访问 app.UseCors(CorsOptions.AllowAll); //使用OAuth 2.0 密码认证模式 app.UseOAuthAuthorizationServer(OAuthOptions.CreateServerOptions()); //app.UseOAuthBearerTokens(OAuthOptions.CreateServerOptions()); //设置abp基于token的验证方式 app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions); //注册cookie属性 app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, //登录入口 LoginPath = new PathString("/J_Account/Login") }); ////app.UseStaticFiles(); ////app.UseEmbeddedFiles(); //允许暴露嵌入式文件到web中! app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.MapSignalR(); // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 }
public CarcarahOAuth(AppFunc next, OAuthOptions options) { this.next = next; this.options = options; AuthCodeStorage = new AuthorizationCodeStorage(); RefreshTokenStorage = new RefreshTokenStorage(); }
public OAuthController(IOptions <OAuthOptions> config, IHttpClientFactory httpClientFactory, OAuthDbContext dbContext) { _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(); _dbContext = dbContext; _oAuthOptions = config?.Value ?? throw new ArgumentNullException(); }
public static IApplicationBuilder UseOAuth(this IApplicationBuilder app, OAuthOptions options) { Ensure.IsNotNull(app, nameof(app)); Ensure.IsNotNull(options, nameof(options)); app.UseMiddleware <OAuthMiddleware>(Options.Create(options)); return(app); }
public OAuthController( ILogger <OAuthController> logger, IOptions <OAuthOptions> options, AccountLinkingStateService stateService) { _logger = logger; _options = options.Value; _stateService = stateService; }
private void ConfigureGitHubConnector(OAuthOptions options) { options.ClientId = Configuration["GitHub:ClientId"]; options.ClientSecret = Configuration["GitHub:ClientSecret"]; options.CallbackPath = new PathString(Configuration["GitHub:CalbackPath"]); options.AuthorizationEndpoint = Configuration["GitHub:AuthroziationEndpoint"]; options.TokenEndpoint = Configuration["GitHub:TokenEndpoint"]; options.UserInformationEndpoint = Configuration["GitHub:UserInfoEndpoint"]; }
/// <summary> /// Creates a new endpoint with an absolute URI. /// </summary> /// <param name="uri">The base URI of the REST API. Missing trailing slash will be appended automatically.</param> /// <param name="oAuthOptions">Options for OAuth 2.0 / OpenID Connect authentication. (optional)</param> /// <param name="httpMessageHandler">The HTTP message handler used to communicate with the remote element. (optional)</param> /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param> /// <param name="errorHandler">Handles errors in HTTP responses. Leave unset for default implementation.</param> /// <param name="linkHandler">Detects links in HTTP responses. Leave unset for default implementation.</param> public OAuthEntryEndpoint(Uri uri, OAuthOptions oAuthOptions = null, HttpMessageHandler httpMessageHandler = null, MediaTypeFormatter serializer = null, IErrorHandler errorHandler = null, ILinkHandler linkHandler = null) : base( uri, new HttpClient(oAuthOptions == null ? httpMessageHandler : new OAuthHandler(oAuthOptions, httpMessageHandler)), serializer, errorHandler, linkHandler) { }
/// <summary> /// Authenticate users using OAuth. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="configureOptions">Configures the middleware options.</param> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> public static IApplicationBuilder UseOAuthAuthentication([NotNull] this IApplicationBuilder app, [NotNull] Action <OAuthOptions> configureOptions) { var options = new OAuthOptions(); if (configureOptions != null) { configureOptions(options); } return(app.UseOAuthAuthentication(options)); }
public static void SetOAuth2Options(OAuthOptions options) { options.ClientId = "1"; options.ClientSecret = "secretkeyforassignment"; //options.AuthorizationEndpoint = "<given authorization endpoint>"; //options.TokenEndpoint = "<given token endpoint>"; //options.UserInformationEndpoint = "<given user information endpoint>"; options.CallbackPath = new PathString("/login"); // Set the scopes you want to request options.Scope.Add("user-read"); options.Scope.Add("user-write"); // Define how to map returned user data to claims options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "Id"); options.ClaimActions.MapJsonKey(ClaimTypes.Email, "Email", ClaimValueTypes.Email); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "UserName"); // Register to events options.Events = new OAuthEvents { // After OAuth2 has authenticated the user OnCreatingTicket = async context => { // Create the request message to get user data via the backchannel var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); // Additional header if needed. Here's an example to go through Azure API Management // request.Headers.Add("Ocp-Apim-Subscription-Key", "<given key>"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Query for user data via backchannel var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); // Parse user data into an object var user = JObject.Parse(await response.Content.ReadAsStringAsync()); // Store the received authentication token somewhere. In a cookie for example context.HttpContext.Response.Cookies.Append("token", context.AccessToken); // Execute defined mapping action to create the claims from the received user object // context.RunClaimActions(JObject.FromObject(user)); }, OnRemoteFailure = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Failure.Message); return(Task.FromResult(0)); } }; }
public static void SetOAuth2Options(OAuthOptions options) { options.ClientId = "chartfield"; options.ClientSecret = "gmXC+5ZfKFi0ED3UYt4AkjkrwB+0pL8VP7pNjoBJcqLpoiQZ1QchXLzMyAOx/RG2PUl7SC8wgu9d0251ZMq6zZFBWsM3pjiJfyMOMTo8Bt9KoLH+1Vdc+lKDolE0mGF01cpz0uHPn59V6nQlTVGsDEsSP4vSkjF0yqh+xfNDIH0=" .Decrypt(); options.AuthorizationEndpoint = "https://login.uiowa.edu/uip/auth.page"; options.TokenEndpoint = "https://login.uiowa.edu/uip/token.page"; //options.UserInformationEndpoint = "<given user information endpoint>"; options.CallbackPath = new PathString("/Account/Login"); // Set the scopes you want to request options.Scope.Add("user-read"); options.Scope.Add("user-write"); // Define how to map returned user data to claims options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "UnivId"); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "HawkId"); // Register to events options.Events = new OAuthEvents { // After OAuth2 has authenticated the user OnCreatingTicket = async context => { // Create the request message to get user data via the backchannel var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); // Additional header if needed. Here's an example to go through Azure API Management // request.Headers.Add("Ocp-Apim-Subscription-Key", "<given key>"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Query for user data via backchannel var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); // Parse user data into an object var user = JObject.Parse(await response.Content.ReadAsStringAsync()); // Store the received authentication token somewhere. In a cookie for example context.HttpContext.Response.Cookies.Append("token", context.AccessToken); // Execute defined mapping action to create the claims from the received user object context.RunClaimActions(JObject.FromObject(user)); }, OnRemoteFailure = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Failure.Message); return(Task.FromResult(0)); } }; }
private static void PrepareClaimActions(OAuthOptions options) { options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name"); options.ClaimActions.MapJsonKey("urn:github:login", "login"); options.ClaimActions.MapJsonKey("urn:github:url", "html_url"); options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url"); options.ClaimActions.MapJsonKey("urn:github:email", "email"); options.ClaimActions.MapJsonKey("urn:github:bio", "bio"); options.ClaimActions.MapJsonKey("urn:github:created_at", "created_at"); }
/// <summary> /// Sets the events. /// </summary> private static void SetEvents(OAuthOptions options, bool addEmailToClaim) { options.Events = new OAuthEvents { OnCreatingTicket = async context => { // return store_id from response var storeId = context.TokenResponse.Response.Value <string>("store_id"); if (addEmailToClaim) { // generate link to Ecwid profile var requestUrl = GenerateRequestUrl(context, storeId); // request account email var accountEmail = await RequestAccountEmail(requestUrl, context); // save email to the claim if (!string.IsNullOrWhiteSpace(accountEmail)) { context.Identity.AddClaim(new Claim( ClaimTypes.Email, accountEmail, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } } // save token to the claim if (!string.IsNullOrWhiteSpace(context.AccessToken)) { context.Identity.AddClaim(new Claim( EcwidClaimTypes.Token, context.AccessToken, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } // save store-id to the claim if (!string.IsNullOrWhiteSpace(storeId)) { context.Identity.AddClaim(new Claim( ClaimTypes.NameIdentifier, storeId, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } var scope = context.TokenResponse.Response.Value <string>("scope"); // save scope to the claim if (!string.IsNullOrWhiteSpace(scope)) { context.Identity.AddClaim(new Claim( EcwidClaimTypes.Scope, scope, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } } }; }
public Startup(IConfiguration configuration) { Configuration = configuration; SwaggerOptions = new SwaggerOptions(); OAuthOptions = new OAuthOptions(); Configuration.GetSection(nameof(SwaggerOptions)).Bind(SwaggerOptions); Configuration.GetSection(nameof(OAuthOptions)).Bind(OAuthOptions); }
private void ConfigureGitLabOAuth(OAuthOptions options) { var cfg = Configuration.GetSection("GitLab"); options.ClientId = cfg["clientId"]; options.ClientSecret = cfg["clientSecret"]; options.CallbackPath = new PathString(cfg["callbackPath"]); options.AuthorizationEndpoint = $"{cfg["url"]}/oauth/authorize"; options.TokenEndpoint = $"{cfg["url"]}/oauth/token"; options.UserInformationEndpoint = $"{cfg["url"]}/api/v4/user"; }
public static void GoogleOAuth2Options(OAuthOptions options) { // TODO: move this into a config file options.ClientId = "1061335654991-o23odngegp0k14th335s3cf39m8kuhrs.apps.googleusercontent.com"; options.ClientSecret = "_MaGsHaes057tndh0KoR1LWO"; options.AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth"; options.TokenEndpoint = "https://oauth2.googleapis.com/token"; options.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo"; options.Scope.Add("profile"); options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "UserId"); options.ClaimActions.MapJsonKey(ClaimTypes.Email, "Email", ClaimValueTypes.Email); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "Name"); // After OAuth2 has authenticated the user options.Events = new OAuthEvents { // After OAuth2 has authenticated the user OnCreatingTicket = async context => { // Create the request message to get user data via the backchannel var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); // Additional header if needed. Here's an example to go through Azure API Management request.Headers.Add("Ocp-Apim-Subscription-Key", "<given key>"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Query for user data via backchannel var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); // Parse user data into an object var user = JObject.Parse(await response.Content.ReadAsStringAsync()); // Store the received authentication token somewhere. In a cookie for example context.HttpContext.Response.Cookies.Append("token", context.AccessToken); // Execute defined mapping action to create the claims from the received user object context.RunClaimActions(JObject.FromObject(user)); }, OnRemoteFailure = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Failure.Message); return(Task.FromResult(0)); } }; }
private static void SetOAuth2Options(OAuthOptions options, string clientId, string clientSecret, bool addEmailToClaim) { options.CallbackPath = new PathString("/signin-ecwid"); options.AuthorizationEndpoint = EcwidDefaults.AuthorizationEndpoint; options.TokenEndpoint = EcwidDefaults.TokenEndpoint; options.UserInformationEndpoint = EcwidDefaults.UserInformationEndpoint; options.ClaimsIssuer = "OAuth2-Ecwid"; options.ClientId = clientId; options.ClientSecret = clientSecret; SetEvents(options, addEmailToClaim); }
private string GetToken(ClaimsIdentity identity) { var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: OAuthOptions.ISSUER, audience: OAuthOptions.AUDIENCE, claims: identity.Claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(OAuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(OAuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }
public async Task Multiple_requests_reuse_the_same_token(string methodName, OAuthOptions options, Uri requestUri, string accessToken, long expiresIn, TestClock clock) { Clock.Set(clock); var method = new HttpMethod(methodName); var httpOptions = new List <HttpMessageOptions>(); var refreshTokenOptions = new HttpMessageOptions { HttpMethod = HttpMethod.Post, RequestUri = new Uri(requestUri, "/oauth/v1/token"), HttpContent = new FormUrlEncodedContent(new Dictionary <string, string> { ["grant_type"] = "refresh_token", ["client_id"] = options.ClientId, ["client_secret"] = options.SecretKey, ["redirect_uri"] = options.RedirectUri.ToString(), ["refresh_token"] = options.RefreshToken }), HttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.FromObject(new { access_token = accessToken, expires_in = expiresIn }) } }; httpOptions.Add(refreshTokenOptions); var option = new HttpMessageOptions { RequestUri = requestUri, HttpMethod = method, HttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) }; httpOptions.Add(option); var client = CreateClient(options, httpOptions.ToArray()); for (int i = 0; i < 2; i++) { var testRequest = new HttpRequestMessage(method, requestUri); await client.SendAsync(testRequest); } Assert.That(refreshTokenOptions.NumberOfTimesCalled, Is.EqualTo(1)); }
public async Task <Token> GetTokenAsync(OAuthOptions options, CancellationToken cancellationToken) { _httpClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); _httpClient.DefaultRequestHeaders.Add("return-client-request-id", "true"); _httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); var data = new Dictionary <string, string> { { "resource", options.Resource.ToString() }, { "client_id", options.ClientId }, { "client_secret", options.ClientSecret }, { "username", options.Username }, { "password", options.Password }, { "scope", "openid" }, { "response_mode", "form_post" }, { "grant_type", "password" } }; using var content = new FormUrlEncodedContent(data); var response = await _httpClient .PostAsync(options.AuthorizationUri, content, cancellationToken); if (!response.IsSuccessStatusCode) { // {"error":"invalid_client","error_description":"MSIS9607: The \u0027client_id\u0027 parameter in the request is invalid. No registered client is found with this identifier."} var responseData = string.Empty; if (response.Content != null) { responseData = await response.Content.ReadAsStringAsync(); } //throw new OAuthApiException( // "The HTTP status code of the response was not expected (" + (int)response.StatusCode + ").", // (int)response.StatusCode, // responseData, // response.Headers.ToDictionary(x => x.Key, x => x.Value), null); _logger.LogError("Error getting OAuth for {Resource} using {ClientId} : {HttpStatus} - {ErrorMessage}", options.Resource, options.ClientId, response.StatusCode, responseData); throw new OAuthApiException("Error getting OAuth token", (int)response.StatusCode, responseData, new Dictionary <string, string>(), string.Empty); } await using var stream = await response.Content .ReadAsStreamAsync(); var token = await JsonSerializer.DeserializeAsync <Token>(stream, cancellationToken : cancellationToken); return(token); }
/// <summary> /// Initializes a new instance of the <see cref="OAuthEventsHandler"/> class. /// </summary> /// <param name="options">The <see cref="OAuthOptions"/> to use.</param> /// <param name="events">The <see cref="ExternalAuthEvents"/> to use.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use.</param> public OAuthEventsHandler(OAuthOptions options, ExternalAuthEvents events, ILoggerFactory loggerFactory) { _options = options; _wrapped = options.Events; _logger = loggerFactory.CreateLogger <OAuthEventsHandler>(); // Setup custom handlers OnRemoteFailure = HandleRemoteFailure; OnTicketReceived = HandleTicketReceived; // Assign delegated handlers OnCreatingTicket = _wrapped.CreatingTicket; OnRedirectToAuthorizationEndpoint = events?.OnRedirectToOAuthAuthorizationEndpoint ?? _wrapped.RedirectToAuthorizationEndpoint; }
public async Task AddAsync_should_add_generic_handler() { var eventCalled = false; Task onTicketReceived(TicketReceivedContext context) { eventCalled = true; return(Task.CompletedTask); } var provider = CreateServiceProvider(options => { options.AddScheme <OAuthOptions, FakeGenericHandler <OAuthOptions> >("test", configure => { configure.Events.OnTicketReceived = onTicketReceived; }); }); var oAuthOptions = new OAuthOptions { ClientId = "test" }; var scheme = Guid.NewGuid().ToString(); var definition = new TSchemeDefinition { Scheme = scheme, DisplayName = "test", HandlerType = typeof(FakeGenericHandler <OAuthOptions>), Options = oAuthOptions }; var sut = provider.GetRequiredService <AuthenticationSchemeProviderWrapper>(); Assert.Contains(typeof(FakeGenericHandler <OAuthOptions>), sut.GetManagedHandlerTypes()); await sut.AddAsync(definition); var state = await VerifyAddedAsync <OAuthOptions>(scheme, provider); var httpContext = new Mock <HttpContext>().Object; state.options.Events.OnTicketReceived(new TicketReceivedContext( httpContext, state.scheme as AuthenticationScheme, state.options as OAuthOptions, new AuthenticationTicket(new ClaimsPrincipal(), scheme))); Assert.True(eventCalled); }
public LaunchpadOptions(Uri launchpadUri, OAuthOptions oauthOptions) { if (launchpadUri == null) { throw new ArgumentNullException(nameof(launchpadUri)); } if (oauthOptions == null) { throw new ArgumentNullException(nameof(oauthOptions)); } LaunchpadUri = launchpadUri; OAuthOptions = oauthOptions; }