protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var state = GetStateFromCookie(); if (state == null) { return(Task.FromResult(HandleRequestResult.Fail("Invalid state cookie."))); } DeleteStateCookie(); var loginResultProtected = Request.Query["loginResult"]; if (string.IsNullOrEmpty(loginResultProtected)) { return(Task.FromResult(HandleRequestResult.Fail("Missing login result."))); } var loginResult = _loginResultProtector.Unprotect(loginResultProtected); if (loginResult == null || !loginResult.IsSuccessful) { return(Task.FromResult(HandleRequestResult.Fail("Invalid login result."))); } var properties = state.AuthenticationProperties; var ticket = GetAuthenticationTicket(loginResult, properties); _logger.BankIdAuthenticationTicketCreated(loginResult.PersonalIdentityNumber); return(Task.FromResult(HandleRequestResult.Success(ticket))); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { SAMLResponseDto samlResponse = null; if (Request.Method == "GET") { samlResponse = SAMLResponseDto.Build(Request.Query.ToDictionary(k => k.Key, k => k.Value.First())); } else { samlResponse = SAMLResponseDto.Build(Request.Form.ToDictionary(k => k.Key, k => k.Value.First())); } try { var properties = Options.StateDataFormat.Unprotect(samlResponse.RelayState); if (properties == null) { return(HandleRequestResult.Fail("The state was missing or invalid.")); } var assertion = await Validate(samlResponse, CancellationToken.None); var claimsIdentity = new ClaimsIdentity(BuildClaims(assertion), Scheme.Name); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var ticket = new AuthenticationTicket(claimsPrincipal, properties, Options.SignInScheme); return(HandleRequestResult.Success(ticket)); } catch (SamlException ex) { return(HandleRequestResult.Fail(ex)); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { //Request.BodyReader //Utf8JsonReader sdf = new Utf8JsonReader(); var input = await new StreamReader(Request.Body).ReadToEndAsync(); var jd = JsonDocument.Parse(input); var requestUrl = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, new Dictionary <string, string> { { "appid", Options.AppId }, { "secret", Options.Secret }, { "js_code", jd.RootElement.GetString("code") }, { "grant_type", "authorization_code" }, }); var response = await Backchannel.GetAsync(requestUrl, Context.RequestAborted); if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"An error occurred when retrieving wechar mini program user information ({response.StatusCode}). Please check if the authentication information is correct and the corresponding Microsoft Account API is enabled."); } //正式处理 var rt = JsonSerializer.Deserialize <MiniProgramToken>(await response.Content.ReadAsStringAsync()); //调试 //var rt = new MiniProgramToken //{ // errcode = 0, // errmsg = "", // openid = "1111111", // session_key = "222", // unionid = "" //}; if (rt.errcode != 0) { throw new HttpRequestException($"errcode:{rt.errcode}, errmsg:{rt.errmsg}"); } var identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, rt.openid), new Claim(nameof(rt.session_key), rt.session_key), new Claim(nameof(rt.unionid), rt.unionid) }, ClaimsIssuer); var authenticationProperties = new AuthenticationProperties { ExpiresUtc = base.Clock.UtcNow.AddMinutes(5), IsPersistent = true, IssuedUtc = Clock.UtcNow }; var ticket = await CreateTicketAsync(identity, authenticationProperties, rt, jd.RootElement); return(HandleRequestResult.Success(ticket)); }
public HandleRequestResult HandleRequest(string message) { HandleRequestResult result = new HandleRequestResult(); PathRequestResponce pathResponce = new PathRequestResponce(); var recognitionResponce = _recognitionService.TryRecogniseAddress(message); switch (recognitionResponce.RecognitionStatus) { case APIAI.Models.RecognitionStatus.Valid: pathResponce = _pathRequestHandler.GetBestPath(recognitionResponce.Address, recognitionResponce.TravelingType); break; case APIAI.Models.RecognitionStatus.Invalid: result.StuckReason = ProgressStuckReason.PhraseNotParsed; result.TextToDisplay = recognitionResponce.QuestionToAsk; return(result); case APIAI.Models.RecognitionStatus.AddressMissing: result.StuckReason = ProgressStuckReason.AddressMissing; result.TextToDisplay = recognitionResponce.QuestionToAsk; return(result); } result.TextToDisplay = pathResponce.PathInsructions; return(result); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var state = GetStateFromCookie(); if (state == null) { return(HandleRequestResult.Fail("Invalid state cookie.")); } DeleteStateCookie(); var sessionId = Request.Query["grandidsession"]; if (string.IsNullOrEmpty(sessionId)) { return(HandleRequestResult.Fail("Missing grandidsession from GrandID.")); } try { var sessionResult = await GetSessionResponseAsync(sessionId); var properties = state.AuthenticationProperties; var ticket = GetAuthenticationTicket(sessionResult, properties); return(HandleRequestResult.Success(ticket)); } catch { return(HandleRequestResult.Fail("Failed to get session from GrandID.")); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { try { var code = Request.Query["code"].ToString(); var state = Request.Query["state"].ToString(); if (code == null) { return(HandleRequestResult.Fail("Code was not found.")); } var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } if (ValidateCorrelationId(properties) == false) { return(HandleRequestResult.Fail("Correlation failed.")); } var token = await InnerClient.GetTokenAsync( code, Context.RequestAborted); if (string.IsNullOrWhiteSpace(token.AccessToken)) { return(HandleRequestResult.Fail("OAuth token endpoint failure.")); } var openId = await InnerClient.GetOpenIdAsync( token.AccessToken, Context.RequestAborted); if (string.IsNullOrWhiteSpace(openId.OpenId)) { return(HandleRequestResult.Fail("openid was not found.")); } var user = await InnerClient.GetUserAsync( token.AccessToken, openId.OpenId, Context.RequestAborted); var qqConnectProfile = QQConnectProfile.From(Scheme.Name, token, openId, user); var principal = qqConnectProfile.BuildClaimsPrincipal(); var ticket = new AuthenticationTicket(principal, properties, Scheme.Name); return(HandleRequestResult.Success(ticket)); } catch (Exception ex) { return(HandleRequestResult.Fail(ex)); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var properties = new AuthenticationProperties(); var form = await Request.ReadFormAsync(); Console.WriteLine("PRINTING FORM"); foreach (var key in form.Keys) { Console.WriteLine($"{key} : {form[key]}"); } var http = new HttpClient(); Console.WriteLine($"{HtmlEncoder.Default.Encode($"{this.Request.Scheme}://{this.Request.Host}/signin-oidc")}"); http.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); var resp = await http.PostAsync("https://login.microsoftonline.com/9fc05d5c-d237-4598-9f9c-65b71fb914ab/oauth2/token", new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("grant_type", "authorization_code"), new KeyValuePair <string, string>("client_id", "eb28e386-ad93-429e-9820-4c7e9b7152d5"), new KeyValuePair <string, string>("code", form["code"]), new KeyValuePair <string, string>("redirect_uri", $"{HtmlEncoder.Default.Encode($"{Environment.GetEnvironmentVariable("PROTOCOL") ?? "http"}://{this.Request.Host}/signin-oidc")}"), new KeyValuePair <string, string>("client_secret", $"{HtmlEncoder.Default.Encode("Vpr4gYm1O5aVjYzELlO0zOW0tJv8kElq/UelqLNnDV8=")}") } )); var content = await resp.Content.ReadAsStringAsync(); Console.WriteLine(content); properties.RedirectUri = form["state"]; Console.WriteLine(properties.RedirectUri); var authorizationResponse = new OpenIdConnectMessage(content); //retrieve redirect URL //resp.EnsureSuccessStatusCode(); SecurityToken validatedToken; var validationParameters = new TokenValidationParameters(); validationParameters.ValidateAudience = false; validationParameters.ValidateIssuer = false; validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(Options.Configuration.SigningKeys) ?? Options.Configuration.SigningKeys; var validatedTokenResponse = Options.SecurityTokenValidator.ValidateToken(authorizationResponse.AccessToken, validationParameters, out validatedToken); //authorizationResponse = new OpenIdConnectMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value))); var msg = new OpenIdConnectMessage { AccessToken = authorizationResponse.AccessToken, IdToken = authorizationResponse.IdToken, RefreshToken = authorizationResponse.RefreshToken, ExpiresIn = authorizationResponse.ExpiresIn, RedirectUri = authorizationResponse.RedirectUri }; SaveTokens(properties, msg); return(HandleRequestResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(validatedTokenResponse.Identity), properties, Scheme.Name))); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { AuthenticationProperties properties = new AuthenticationProperties(); properties.Load(Request, Options.StateDataFormat); var(id, message) = await ExtractInfoFromAuthenticationResponse(); try { var idpName = properties.GetIdentityProviderName(); var request = properties.GetAuthenticationRequest(); var validationMessageResult = await ValidateAuthenticationResponse(message, request, properties, idpName); if (validationMessageResult != null) { return(validationMessageResult); } var responseMessageReceivedResult = await _eventsHandler.HandleAuthenticationResponseMessageReceived(Context, Scheme, Options, properties, message); if (responseMessageReceivedResult.Result != null) { return(responseMessageReceivedResult.Result); } message = responseMessageReceivedResult.ProtocolMessage; properties = responseMessageReceivedResult.Properties; var correlationValidationResult = ValidateCorrelation(properties); if (correlationValidationResult != null) { return(correlationValidationResult); } var(principal, validFrom, validTo) = CreatePrincipal(message); AdjustAuthenticationPropertiesDates(properties, validFrom, validTo); properties.SetSubjectNameId(message.GetAssertion().Subject?.GetNameID()?.Value); properties.SetSessionIndex(message.GetAssertion().GetAuthnStatement().SessionIndex); properties.Save(Response, Options.StateDataFormat); var ticket = new AuthenticationTicket(principal, properties, Scheme.Name); await _eventsHandler.HandleAuthenticationSuccess(Context, Scheme, Options, id, ticket); return(HandleRequestResult.Success(ticket)); } catch (Exception exception) { Logger.ExceptionProcessingMessage(exception); var authenticationFailedResult = await _eventsHandler.HandleAuthenticationFailed(Context, Scheme, Options, message, exception); return(authenticationFailedResult.Result ?? HandleRequestResult.Fail(exception, properties)); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { AuthenticationProperties properties = null; var query = Request.Query; var error = query["error"]; if (!string.IsNullOrEmpty(error)) { var errorUri = query["error_uri"]; var errorDescription = query["error_description"]; var errorMsg = $"[ErrorUri: {errorUri}] [ErrorDescription: {errorDescription}]"; return(HandleRequestResult.Fail(errorMsg)); } var code = query["code"]; var state = query["state"]; properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } if (StringValues.IsNullOrEmpty(code)) { return(HandleRequestResult.Fail("Code was not found.")); } var tokens = await ExchangeCodeAsync(code, BuildRedirectUri(Options.CallbackPath)); if (tokens.Error != null) { return(HandleRequestResult.Fail(tokens.Error)); } if (string.IsNullOrEmpty(tokens.AccessToken)) { return(HandleRequestResult.Fail("Failed to retrieve access token.")); } var identity = new ClaimsIdentity(Options.ClaimsIssuer); AuthenticationTicket ticket = await CreateTicketAsync(identity, properties, tokens); if (ticket != null) { return(HandleRequestResult.Success(ticket)); } else { return(HandleRequestResult.Fail("Failed to retrieve user information from remote server.")); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { // Taken from the base class' implementation so we can modify the status code check // for "access denied" as LinkedIn uses non-standard error codes (see https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers/issues/480). // https://github.com/dotnet/aspnetcore/blob/bbf7c8780c42e3d32aeec8018367037784eb9181/src/Security/Authentication/OAuth/src/OAuthHandler.cs#L49-L87 var query = Request.Query; var state = query["state"]; var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties)) { return(HandleRequestResult.Fail("Correlation failed.", properties)); } var error = query["error"]; if (!StringValues.IsNullOrEmpty(error)) { // Note: access_denied errors are special protocol errors indicating the user didn't // approve the authorization demand requested by the remote authorization server. // Since it's a frequent scenario (that is not caused by incorrect configuration), // denied errors are handled differently using HandleAccessDeniedErrorAsync(). // Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information. var errorDescription = query["error_description"]; var errorUri = query["error_uri"]; // See https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow#application-is-rejected if (StringValues.Equals(error, "access_denied") || StringValues.Equals(error, "user_cancelled_login") || StringValues.Equals(error, "user_cancelled_authorize")) { var result = await HandleAccessDeniedErrorAsync(properties); if (!result.None) { return(result); } var deniedEx = new Exception("Access was denied by the resource owner or by the remote server."); deniedEx.Data["error"] = error.ToString(); deniedEx.Data["error_description"] = errorDescription.ToString(); deniedEx.Data["error_uri"] = errorUri.ToString(); return(HandleRequestResult.Fail(deniedEx, properties)); } } return(await base.HandleRemoteAuthenticateAsync()); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { try { return(await base.HandleRemoteAuthenticateAsync()); } catch (UnauthorizedAccessException e) { return(HandleRequestResult.Fail(e)); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { IQueryCollection query = Request.Query; var state = query["state"]; var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } string ticket = query["ticket"].FirstOrDefault(); string returnUrl = query["returnUrl"].FirstOrDefault(); if (ticket == null) { return(HandleRequestResult.Fail("Ticket should never be null.")); } string serviceUri = CurrentUri; string userInformationUrl = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, new Dictionary <string, string> { ["ticket"] = ticket, ["service"] = GetService(CurrentUri) }); HttpResponseMessage response = await Backchannel.GetAsync(userInformationUrl); var xdoc = XDocument.Load(await response.Content.ReadAsStreamAsync()); string xmlErrorMessage = GetXmlErrorMessage(xdoc); if (xmlErrorMessage != null) { return(HandleRequestResult.Fail(xmlErrorMessage)); } IEnumerable <Claim> claims = GetXmlClaims(xdoc); var identity = new ClaimsIdentity(claims, ClaimsIssuer); var token = OAuthTokenResponse.Failed(new Exception("Token not available.")); AuthenticationTicket authenticationTicket = await CreateTicketAsync(identity, properties, token); if (authenticationTicket != null) { return(HandleRequestResult.Success(authenticationTicket)); } else { return(HandleRequestResult.Fail("Failed to retrieve user information from remote user.", properties)); } }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { TelegramOAuthHandler telegramOAuthHandler = this; LoginWidget loginWidget = new LoginWidget(telegramOAuthHandler.Options.ClientSecret); Dictionary <string, string> parameters = telegramOAuthHandler.Context.Request.Query.Keys.ToDictionary(k => k, v => telegramOAuthHandler.Context.Request.Query[v].FirstOrDefault()); Authorization authorized = loginWidget.CheckAuthorization(parameters); if (authorized != Authorization.Valid) { return(HandleRequestResult.Fail($"Authorization state: {authorized}")); } TelegramUser telegramUser = new TelegramUser(parameters[Fields.Id]); ClaimsIdentity identity = new ClaimsIdentity(new[] { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", telegramUser.Id, "http://www.w3.org/2001/XMLSchema#string", telegramOAuthHandler.ClaimsIssuer), //new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", telegramUser.Username,"http://www.w3.org/2001/XMLSchema#string", telegramOAuthHandler.ClaimsIssuer) }, telegramOAuthHandler.ClaimsIssuer); AuthenticationProperties authenticationProperties = null; var cookie = Request.Cookies["__Telegram"]; if (string.IsNullOrEmpty(cookie)) { return(HandleRequestResult.Fail("State cookie not present")); } authenticationProperties = telegramOAuthHandler.Options.StateDataFormat.Unprotect(cookie); if (authenticationProperties == null) { return(HandleRequestResult.Fail("Authentication properties null")); } JObject user = JObject.FromObject(telegramUser); Response.Cookies.Delete("__Telegram"); return(HandleRequestResult.Success(await telegramOAuthHandler.CreateTicketAsync(identity, authenticationProperties, OAuthTokenResponse.Success(user)))); }
//response from identity provider hits here /// <summary> /// Authenticate the user identity with the identity provider. /// The method process the request on the endpoint defined by CallbackPath. /// </summary> /// <returns></returns> protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { // assumption: if the ContentType is "application/x-www-form-urlencoded" it should be safe to read as it is small. if (HttpMethods.IsPost(Request.Method) && !string.IsNullOrEmpty(Request.ContentType) // May have media/type; charset=utf-8, allow partial match. && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Request.Body.CanRead && Request.Path.Value.EndsWith(Options.CallbackPath, StringComparison.OrdinalIgnoreCase)) { return(await HandleSignIn()); } else { return(HandleRequestResult.Fail("an error occured")); } }
protected async override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { if (Context.Request.Cookies.TryGetValue("RequestToken", out var requestToken)) { var res = await GetAccessTokenAsync(requestToken); if (res.IsSuccess && res.PocketAccessTokenRespons != null) { var ticket = CreatePocketTicketAsync(res.PocketAccessTokenRespons); if (Context.Request.Cookies.TryGetValue("RedirectUri", out var redirectUri)) { ticket.Properties.RedirectUri = redirectUri; } return(HandleRequestResult.Success(ticket)); } } return(HandleRequestResult.Fail(new ArgumentNullException("RequestToken"))); }
/// <InheritDocs /> protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var requestData = Context.ToHttpRequestData(dataProtector.Unprotect); var commandResult = CommandFactory.GetCommand(CommandFactory.AcsCommandName) .Run(requestData, Options); var properties = new AuthenticationProperties(commandResult.RelayData) { RedirectUri = commandResult.Location.OriginalString }; var ticket = new AuthenticationTicket( commandResult.Principal, properties, Scheme.Name); return(Task.FromResult(HandleRequestResult.Success(ticket))); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var protectedText = Request.Query["state"].ToArray().FirstOrDefault(); var properties = Options.StateDataFormat.Unprotect(protectedText); // simulator token return from oauth server var tokenObject = Options.PassthroughTokenHandler?.Invoke() ?? new { token_type = "bearer", access_token = "1234567890", refresh_token = "0987654321", expires_in = "3600", user_id = "nepton_h23f620G2Xw2812aM3a9Z", screen_name = "nepton", }; var token = OAuthTokenResponse.Success(JsonDocument.Parse(JsonSerializer.Serialize(tokenObject))); if (token.Error != null) { return(HandleRequestResult.Fail(token.Error, properties)); } var identity = new ClaimsIdentity(ClaimsIssuer); var context = new OAuthCreatingTicketContext( new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, token, token.Response.RootElement); context.RunClaimActions(); await OAuthEvents.CreatingTicket(context); var ticket = new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name); return(HandleRequestResult.Success(ticket)); }
/// <summary> /// This method handles the routing of a request that the middleware is working with to the correct logic /// </summary> /// <returns>Handle which indicates that the request has been responded to or Success if the user has been logged in</returns> protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { Logger.LogTrace("Started working on request"); CommandWorker.Request = Request; CommandWorker.Response = Response; CommandWorker.Options = Options; //Options will probably never change but to make sure the static object is up to date lets set it if (Request.Query.ContainsKey("nut")) //Generally requests from a SQRL client { Logger.LogInformation("Processing nut request"); CommandWorker.NutRequest(); } else if (Request.Query.ContainsKey("check")) //Helper for initial page to check when a user has logged in { Logger.LogInformation("Processing check request"); return(CheckRequest()); } else if (Request.Query.ContainsKey("cps")) { Logger.LogInformation("Processing cps request"); return(CheckCpsRequest()); } else if (Request.Query.ContainsKey("diag") && Options.Diagnostics) { Logger.LogInformation("Processing diag request"); return(DiagnosticsPage()); } else if (Request.Query.ContainsKey("helper")) { Logger.LogInformation("Processing helper request"); CommandWorker.HelperJson(); } else if (!Options.DisableDefaultLoginPage) //For everything else we should only return a login page { Logger.LogInformation("Processing default login page request"); CommandWorker.QrCodePage(); } Logger.LogTrace("Finished working on request"); return(Task.FromResult(HandleRequestResult.Handle())); }
/// <summary> /// Derived types may override this method to handle access denied errors. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <returns>The <see cref="HandleRequestResult"/>.</returns> protected virtual async Task <HandleRequestResult> HandleAccessDeniedErrorAsync(AuthenticationProperties properties) { Logger.AccessDeniedError(); var context = new AccessDeniedContext(Context, Scheme, Options) { AccessDeniedPath = Options.AccessDeniedPath, Properties = properties, ReturnUrl = properties?.RedirectUri, ReturnUrlParameter = Options.ReturnUrlParameter }; await Events.AccessDenied(context); if (context.Result != null) { if (context.Result.Handled) { Logger.AccessDeniedContextHandled(); } else if (context.Result.Skipped) { Logger.AccessDeniedContextSkipped(); } return(context.Result); } // If an access denied endpoint was specified, redirect the user agent. // Otherwise, invoke the RemoteFailure event for further processing. if (context.AccessDeniedPath.HasValue) { string uri = context.AccessDeniedPath; if (!string.IsNullOrEmpty(context.ReturnUrlParameter) && !string.IsNullOrEmpty(context.ReturnUrl)) { uri = QueryHelpers.AddQueryString(uri, context.ReturnUrlParameter, context.ReturnUrl); } Response.Redirect(BuildRedirectUri(uri)); return(HandleRequestResult.Handle()); } return(HandleRequestResult.NoResult()); }
/// <inheritdoc /> protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { //Authenticate user based on SamlResponse var relaystate = BuildRedirectUri("/"); try { return(Task.FromResult(_authnResponseHandler.Handle(Options, Request.HttpContext))); } catch (ParsingException parseEx) { //HTTP 400 = Bad Request Response.StatusCode = 400; return(Task.FromResult(HandleRequestResult.Fail(parseEx))); } catch (Exception ex) { Response.StatusCode = 500; return(Task.FromResult(HandleRequestResult.Fail(ex))); } }
/// <summary> /// 回调处理 /// </summary> /// <returns></returns> protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { try { var code = Request.Query["code"].ToString(); var state = Request.Query["state"].ToString(); if (code == null) { return(HandleRequestResult.Fail("Code was not found.")); } var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } var openId = await InnerClient.GetOpenId( code, Context.RequestAborted); if (string.IsNullOrWhiteSpace(openId.unionid)) { return(HandleRequestResult.Fail("unionid was not found.")); } var qqConnectProfile = DingTalkConnectProfile.From(Scheme.Name, Options.ClientId, openId); var principal = qqConnectProfile.BuildClaimsPrincipal(); var ticket = new AuthenticationTicket(principal, properties, Scheme.Name); return(HandleRequestResult.Success(ticket)); } catch (Exception ex) { return(HandleRequestResult.Fail(ex)); } }
private Task <HandleRequestResult> CheckCpsRequest() { var result = Options.GetUserIdAndRemoveCpsSessionIdInternal(Request.Query["cps"], Context); if (!string.IsNullOrEmpty(result)) { var username = Options.GetUsernameInternal(result, Context); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, result), new Claim(ClaimTypes.Name, username) }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(Task.FromResult(HandleRequestResult.Success(ticket))); } //We are specifically not returning any body in the response here as they clearly don't have a valid purpose to be here return(Task.FromResult(HandleRequestResult.Handle())); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { var detectedDevice = GetDetectedDevice(); var state = GetStateFromCookie(); if (state == null) { return(await HandleRemoteAuthenticateFail("Invalid state cookie", detectedDevice)); } DeleteStateCookie(); var loginResultProtected = Request.Query["loginResult"]; if (string.IsNullOrEmpty(loginResultProtected)) { return(await HandleRemoteAuthenticateFail("Missing login result", detectedDevice)); } var loginResult = _loginResultProtector.Unprotect(loginResultProtected); if (loginResult == null || !loginResult.IsSuccessful) { return(await HandleRemoteAuthenticateFail("Invalid login result", detectedDevice)); } var properties = state.AuthenticationProperties; var ticket = await GetAuthenticationTicket(loginResult, properties); await _bankIdEventTrigger.TriggerAsync(new BankIdAspNetAuthenticateSuccessEvent( ticket, PersonalIdentityNumber.Parse(loginResult.PersonalIdentityNumber), detectedDevice )); return(HandleRequestResult.Success(ticket)); }
protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { ClaimsIdentity identity = new ClaimsIdentity(ClaimsIssuer); IQueryCollection query = Request.Query; StringValues state = query["state"]; AuthenticationProperties properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(Task.FromResult(HandleRequestResult.Fail("The state was missing or invalid."))); } if (!ValidateCorrelationId(properties)) { return(Task.FromResult(HandleRequestResult.Fail("Correlation failed."))); } StringValues codeValues = query["code"]; string code = codeValues.FirstOrDefault(); FormAuthenticationResponse response = ValidateAndGetDataAsync(code, Options.UserInformationEndpoint).Result; if (response.Error != null) { return(Task.FromResult(HandleRequestResult.Fail(response.Error.Message))); } List <Claim> claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, response.NameIdentifier, ClaimValueTypes.String, ClaimsIssuer), new Claim(ClaimTypes.Name, response.Name, ClaimValueTypes.String, ClaimsIssuer), new Claim(ClaimTypes.Email, response.Email, ClaimValueTypes.String, ClaimsIssuer), }; identity.AddClaims(claims); AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.ClaimsIssuer); return(Task.FromResult(HandleRequestResult.Success(ticket))); }
private Task <HandleRequestResult> CheckRequest() { var result = CommandWorker.CheckPage(); if (result != null) { Logger.LogTrace("User is authorized and can be logged in"); var username = Options.GetUsernameInternal(result.Idk, Context); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, result.Idk), new Claim(ClaimTypes.Name, username) }; Logger.LogDebug("The userId is: {0}", result.Idk); Logger.LogDebug("The username is: {0}", username); var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(Task.FromResult(HandleRequestResult.Success(ticket))); } return(Task.FromResult(HandleRequestResult.Handle())); }
protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { try { Logger.LogDebug($"Looking for bearer token! {nameof(HandleRemoteAuthenticateAsync)}"); var v = Request.Headers["Authorization"].FirstOrDefault(); var auth = v?.Split(' ') ?? new string[0]; if (v != null && auth.Length >= 2 && v.Split(' ')[0].Equals("bearer", StringComparison.InvariantCultureIgnoreCase)) { var user = TokenValidator.Validate(v.Split(' ')[1]); Context.User = user; return(Task.FromResult(HandleRequestResult.Success(new AuthenticationTicket(user, Scheme.Name)))); } Logger.LogDebug("No bearer token provided"); return(Task.FromResult(HandleRequestResult.SkipHandler())); } catch (Exception ex) { Logger.LogError(ex, ex.Message); return(Task.FromResult(HandleRequestResult.Fail(ex))); } }
private Task <HandleRequestResult> DiagnosticsPage() { if (Request.Query["diag"] == "clear") { SqrlAuthenticationOptions.TransactionLog.Clear(); } var responseMessage = new StringBuilder(); responseMessage.AppendLine("<h1>Diagnostics</h1>"); foreach (var log in SqrlAuthenticationOptions.TransactionLog) { responseMessage.AppendLine("<div>"); responseMessage.AppendLine("<h2>" + log.RequestUrl + "</h2>"); foreach (var body in log.Body) { responseMessage.AppendLine("<p>" + body + "</p>"); } responseMessage.AppendLine("<h2>Responded with</h2>"); foreach (var body in log.ResponseBody) { responseMessage.AppendLine("<p>" + body + "</p>"); } responseMessage.AppendLine("</div>"); responseMessage.AppendLine("<hr/>"); } responseMessage.AppendLine("<a href=\"/login-sqrl?diag=clear\">Clear logs</a>"); var responseMessageBytes = Encoding.ASCII.GetBytes(responseMessage.ToString()); Response.StatusCode = StatusCodes.Status200OK; Response.ContentType = "text/html"; Response.ContentLength = responseMessageBytes.LongLength; Response.Body.WriteAsync(responseMessageBytes, 0, responseMessageBytes.Length); return(Task.FromResult(HandleRequestResult.Handle())); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { IHeaderDictionary headers = Request.Headers; string timestamp = headers[TimestampHeaderName].FirstOrDefault(); string signature = headers[SignatureHeaderName].FirstOrDefault(); if (timestamp == null) { return(HandleRequestResult.Fail($"Missing header {TimestampHeaderName}")); } if (signature == null) { return(HandleRequestResult.Fail($"Missing header {SignatureHeaderName}")); } bool isNumber = long.TryParse(timestamp, out long timestampAsLong); if (!isNumber) { return(HandleRequestResult.Fail($"Invalid header. Header {TimestampHeaderName} not a number")); } Request.EnableBuffering(); using var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true); string body = await reader.ReadToEndAsync(); Request.Body.Position = 0; if (IsValidDiscordSignature(signature, timestampAsLong, body)) { return(HandleRequestResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), DiscordEventsAuthenticationConstants.AuthenticationScheme))); } return(HandleRequestResult.Fail("Verification of Discord request failed.")); }
protected override Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { if (!Request.Form.ContainsKey("payload")) { return(Task.FromResult(HandleRequestResult.Fail("the response didn't contain payload."))); } var payload = Request.Form["payload"]; var redirectUri = "/"; if (Request.Query.ContainsKey("redirectUri")) { redirectUri = Request.Query["redirectUri"]; } var json = EncryptionHelper.Decrypt(payload, Options.DecryptionKey); var user = JObject.Parse(json); var claims = new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, user.Value <string>("username"), ClaimValueTypes.String, ClaimsIssuer), new Claim(ClaimTypes.Name, user.Value <string>("username"), ClaimValueTypes.String, ClaimsIssuer), }; var roles = (JArray)user["roles"]; claims.AddRange(roles.Select(x => new Claim(ClaimTypes.Role, x.Value <string>(), ClaimValueTypes.String, ClaimsIssuer))); var identity = new ClaimsIdentity(claims, ClaimsIssuer); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { RedirectUri = redirectUri }, Scheme.Name); return(Task.FromResult(HandleRequestResult.Success(ticket))); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { try { var result = await Context.FinishSsoAsync(); if (!result.IsSuccessful) { throw new SamlResponseException(result.PartnerId, result.Status, result.SubStatus); } var properties = new AuthenticationProperties { IssuedUtc = result.SecurityToken.ValidFrom, ExpiresUtc = result.SecurityToken.ValidTo }; var ticket = new AuthenticationTicket(result.Subject, properties, Scheme.Name); return(HandleRequestResult.Success(ticket)); } catch (Exception ex) { return(HandleRequestResult.Fail(ex)); } }