Cześć,
Mam problem z autoryzacją użytkownika, po przez metodę AuthorizeAsync z klasy AuthorizationServiceExtensions.
Używam to w takim kodzie:
public void Remove(int userId, int cryptoinvestId)
{
var user = GetUserById(userId);
var cryptoInvest = _dbContext
.CryptoInvests
.FirstOrDefault(x => x.Id == cryptoinvestId);
var authorizationResult = _authorizationService.AuthorizeAsync(_userContextService.User, cryptoinvestId,
new ResourceOperationRequirement(ResourceOperation.Delete)).Result;
if (!authorizationResult.Succeeded)
{
throw new ForbidException();
}
_dbContext.CryptoInvests.Remove(cryptoInvest);
_dbContext.SaveChanges();
}
authorizationResult ciągle zwraca Failed, mimo tego, że wszystko powinno przechodzić. Możliwe, że nie za bardzo rozumiem jak ta metoda do końca działa. Dodam jeszcze kod z klasy UserContextService:
using System.Security.Claims;
namespace InvestWallet.Services
{
public interface IUserContextService
{
ClaimsPrincipal User { get; }
int? GetUserId { get; }
}
public class UserContextService : IUserContextService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public UserContextService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public ClaimsPrincipal User => _httpContextAccessor.HttpContext?.User;
public int? GetUserId =>
User is null ? null : (int?)int.Parse(User.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value);
}
}
W Postmanie wartość Tokenu umieszczam w nagłówku. Wydaje mi się, że robię wszystko poprawnie jak widziałem i czytałem w internecie. Jak zatrzymuje się debuggerem to wartość zmiennych są poprawne, tylko ten User typu ClaimsPrincipal nie wiem czy do końca jest dobrze. Za podpowiedzi z wytłumaczeniem z góry wielkie DZIĘKUJĘ :)