Hej,
Kilka dobrych godzin kopałem w internecie , próbowałem różne rozwiązania i niestety bez skutku. Problem wygląda tak, że chce pobrać dane dla aktualnie zalogowanego użytkownika (jego obiekt lub przynajmniej id, aby pobrać sobie obiekt). Niestety przy każdym możliwym rozwiązaniu dostaję null, nie mam już pomysłów co robić, a chciałbym rozwiązać ten problem. Jakieś pomysły? Wersja .NET 6.0, jak w tytule.
Liczę, że wspólnie ogarniemy problem. :)
Kod:
Program.cs
using KursAspNetBackend.Database;
using KursAspNetBackend.Domain.Entities;
using KursAspNetBackend.Database.Repositories;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using KursAspNetBackend.Domain.Interfaces.Identity;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
//builder.Services.AddHttpContextAccessor();
///builder.Services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
//builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Adding Transients
builder.Services.AddTransient<IMessagesRepository, MessagesRepository>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
}
app.UseAuthentication();
//app.UseIdentityServer();
app.UseAuthorization();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials()); // allow credentials
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html"); ;
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
}
//app.Services.GetRequiredService<ApplicationDbContext>().Database.EnsureCreated();
app.Run();
AccountController.cs
using KursAspNetBackend.Domain.Entities;
using KursAspNetBackend.Domain.Dtos;
using KursAspNetBackend.Domain.Entities;
using KursAspNetBackend.Domain.Dtos;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace KursAspNetBackend.Controllers
{
[Route("account/")]
public class AccountController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IHttpContextAccessor _httpContextAccessor;
public AccountController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IHttpContextAccessor httpContextAccessor)
{
_userManager = userManager;
_signInManager = signInManager;
_httpContextAccessor = httpContextAccessor;
}
[HttpGet]
[Route("getCurrentUser")]
public async Task<IActionResult> GetCurrentUser()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User);
if(user == null)
{
return Unauthorized();
}
return Ok(user);
}
[HttpPost]
[Route("register")]
public async Task<IActionResult> Register([FromBody] UserRegisterDto userRegisterDto)
{
var newUser = new ApplicationUser
{
Email = userRegisterDto.Email,
UserName = userRegisterDto.Email,
FirstName = userRegisterDto.FirstName,
LastName = userRegisterDto.LastName,
Address = "",
};
var result = await _userManager.CreateAsync(newUser, userRegisterDto.Password);
if (result.Succeeded)
{
var token = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);
await _userManager.ConfirmEmailAsync(newUser, token);
return Ok();
}
else
{
foreach (IdentityError error in result.Errors)
Console.WriteLine($"Oops! {error.Description} ({error.Code}");
}
return NotFound();
}
[HttpPost]
[Route("login")]
public async Task<IActionResult> Login([FromBody] UserLoginDto userLoginDto)
{
var foundUser = await _userManager.FindByEmailAsync(userLoginDto.Email);
if(foundUser == null)
{
return NotFound();
}
var result = await _signInManager.PasswordSignInAsync(foundUser, userLoginDto.Password, true, false);
if (result.Succeeded)
{
return Ok();
}
return NotFound();
}
}
}
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12761",
"sslPort": 0
}
},
"profiles": {
"KursAspNetBackend": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5054",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
}
}
}