Мне удалось успешно войти в систему с использованием аутентификации Facebook, но после этого я получил нулевой access_token
вот мой код:
Homecontroller:
Мне удалось успешно войти в систему с использованием аутентификации Facebook, но после этого я получил нулевой access_token вот мой код: Homecontroller: [code]using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Diagnostics; using TSG.Models; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; using Newtonsoft.Json.Linq; using TSG.Services;
namespace TSG.Controllers { public class HomeController : Controller { private readonly ApplicationDbContext _context; private readonly IFacebookService _facebookService;
// Authenticate the user var authenticatedUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); if (authenticatedUserId != request.UserId) { return Unauthorized("You are not authorized to delete this user's data."); }
// Perform data deletion logic based on the user ID var feedbacks = _context.FeedbackResponses.Where(f => f.UserId == request.UserId).ToList(); if (feedbacks != null) { _context.FeedbackResponses.RemoveRange(feedbacks); await _context.SaveChangesAsync(); }
return Ok("User data deleted successfully."); }
[HttpGet] public async Task ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { // Handle the error appropriately return RedirectToAction("Error", "Home", new { errorMessage = $"Error from external provider: {remoteError}" }); }
var info = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); if (info.Principal == null) { // Handle the error appropriately return RedirectToAction("Error", "Home", new { errorMessage = "Error loading external login information." }); }
var accessToken = await HttpContext.GetTokenAsync("access_token"); _logger.LogInformation("AccessToken Retrieved: {AccessToken}", accessToken); if (string.IsNullOrEmpty(accessToken)) { _logger.LogWarning("Access token is missing."); return RedirectToAction("Error", "Home", new { errorMessage = "Access token is missing." }); }
var userId = userData["id"].ToString(); var userName = userData["name"].ToString(); var userProfilePictureUrl = userData["picture"]["data"]["url"].ToString();
var user = await _context.Users.SingleOrDefaultAsync(u => u.Id == userId); if (user == null) { user = new User { Id = userId, UserName = userName, ProfilePictureUrl = userProfilePictureUrl, DateLoggedIn = DateTime.UtcNow }; _context.Users.Add(user); await _context.SaveChangesAsync(); }
// Sign in the user await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(info.Principal));
// Redirect to the return URL if (returnUrl != null && Url.IsLocalUrl(returnUrl)) { return LocalRedirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } }
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error(string errorMessage = null) { var errorViewModel = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = errorMessage ?? "An error occurred while processing your request." }; return View(errorViewModel); } } }
[/code] Мне удалось успешно войти в систему и получить access_token здесь, во внешних обратных вызовах. feedbackcontroller: [code]using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using TSG.Models; using Newtonsoft.Json.Linq; using Microsoft.AspNetCore.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using TSG.Services;
var userId = userData["id"].ToString(); var userName = userData["name"].ToString(); var userProfilePictureUrl = userData["picture"]["data"]["url"].ToString();
var user = await _context.Users.SingleOrDefaultAsync(u => u.Id == userId); if (user == null) { user = new User { Id = userId, UserName = userName, ProfilePictureUrl = userProfilePictureUrl, DateLoggedIn = DateTime.UtcNow }; _context.Users.Add(user); await _context.SaveChangesAsync(); }
var feedback = new FeedbackResponse { UserId = userId, FeedbackText = model.FeedbackText, JobTitle = model.JobTitle, Relationship = model.Relationship, DateSubmitted = DateTime.Now, User = user };
// Return the Error view if the model state is invalid return RedirectToAction("Error", "Home", new { errorMessage = "The feedback form contains invalid data. Please correct the errors and try again." }); } catch (Exception ex) { _logger.LogError(ex, "Error submitting feedback"); return RedirectToAction("Error", "Home", new { errorMessage = "An error occurred while submitting feedback. Please try again later." }); } } } }
[/code] Но здесь, в разделе «Отправить отзыв», всегда отсутствует access_token... вот мой файл program.cs для справки: [code]using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.EntityFrameworkCore; using TSG.Models; using TSG.Services;
namespace TSG { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args);
// Load secrets from environment variables var tsgDbConnection = Environment.GetEnvironmentVariable("TSGDB_CONNECTION_STRING"); var facebookAppSecret = Environment.GetEnvironmentVariable("FACEBOOK_APP_SECRET"); var googleClientSecret = Environment.GetEnvironmentVariable("GOOGLE_CLIENT_SECRET");
if (string.IsNullOrEmpty(tsgDbConnection) || string.IsNullOrEmpty(facebookAppSecret) || string.IsNullOrEmpty(googleClientSecret)) { throw new ArgumentNullException("One or more environment variables are missing."); }
// Add services to the container. builder.Services.AddControllersWithViews();