Мне нужна помощь с использованием ASP.net Core MVC.. вход в систему прошел успешно, но при проверке я получаю нулевой тоC#

Место общения программистов C#
Ответить
Anonymous
 Мне нужна помощь с использованием ASP.net Core MVC.. вход в систему прошел успешно, но при проверке я получаю нулевой то

Сообщение Anonymous »

Мне удалось успешно войти в систему с использованием аутентификации Facebook, но после этого я получил нулевой access_token
вот мой код:
Homecontroller:

Код: Выделить всё

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;

private readonly ILogger _logger;
public HomeController(ApplicationDbContext context, IFacebookService facebookService, ILogger logger)
{
_context = context;
_facebookService = facebookService;
_logger = logger;
}

public IActionResult Index()
{
return View();
}

public IActionResult Portfolio()
{
var feedbackList = _context.FeedbackResponses
.Include(f => f.User)  // Eagerly load the related User entity
.OrderByDescending(f => f.DateSubmitted)
.Take(10)
.ToList();
return View(feedbackList);
}

public IActionResult Feedbacks()
{
return View();
}

public IActionResult PrivacyPolicy()
{
return View();
}

public IActionResult TermsOfService()
{
return View();
}

public IActionResult CopyrightPolicy()
{
return View();
}

public IActionResult CookiesPolicy()
{
return View();
}

[HttpPost]
[Authorize]
[Route("DataDeletion")]
public async Task DataDeletion([FromBody] DataDeletionRequest request)
{
if (request == null || string.IsNullOrEmpty(request.UserId))
{
return BadRequest("Invalid request.");
}

// 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." });
}

JObject userData = await _facebookService.GetUserProfileAsync(accessToken);

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);
}
}
}

Мне удалось успешно войти в систему и получить access_token здесь, во внешних обратных вызовах.
feedbackcontroller:

Код: Выделить всё

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;

namespace TSG.Controllers
{
public class FeedbackController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IFacebookService _facebookService;
private readonly ILogger _logger;

public FeedbackController(ApplicationDbContext context, IFacebookService facebookService, ILogger logger)
{
_context = context;
_facebookService = facebookService;
_logger = logger;
}

[HttpPost]
[Authorize]
public async Task SubmitFeedback(FeedbackViewModel model)
{
try
{
if (ModelState.IsValid)
{

// Retrieve the access token
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."  });
}

JObject userData = await _facebookService.GetUserProfileAsync(accessToken);

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
};

_context.FeedbackResponses.Add(feedback);
await _context.SaveChangesAsync();

return RedirectToAction("Index", "Home");
}

// 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." });
}
}
}
}

Но здесь, в разделе «Отправить отзыв», всегда отсутствует access_token...
вот мой файл program.cs для справки:

Код: Выделить всё

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();

// Add IHttpContextAccessor
builder.Services.AddHttpContextAccessor();

// Register FacebookService with HttpClient
builder.Services.AddHttpClient();

// Authentication configuration
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = builder.Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = facebookAppSecret;
facebookOptions.Fields.Add("id");
facebookOptions.Fields.Add("name");
facebookOptions.Fields.Add("picture");
facebookOptions.Scope.Add("public_profile");
facebookOptions.Scope.Add("email");
facebookOptions.SaveTokens = true;
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = googleClientSecret;
});

// Database configuration
builder.Services.AddDbContext(options =>
options.UseSqlServer(tsgDbConnection));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
}
}
}
Я пытался создать обычный access_token, но не получилось

Подробнее здесь: https://stackoverflow.com/questions/793 ... tting-null
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»