-1

im trying to get the role claim and verify the it before adding a new user

var role = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Role).Value;

i have already registered service in programs.cs

builder.Services.AddHttpContextAccessor();

and initialized well

  private readonly IHttpContextAccessor _httpContextAccessor;

    public DBService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

Any help would be much appreciated!

step ofori
  • 19
  • 4
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – gunr2171 Jan 12 '23 at 12:40
  • no please ...i already looked through – step ofori Jan 12 '23 at 12:42
  • Then check first if your Claims contain a role claim. If not FindFirst will return null and a call to `.Value` will fail the way you say. – Ralf Jan 12 '23 at 12:43
  • @Ralf yes i have a role claim as part of my claims – step ofori Jan 12 '23 at 12:44
  • 1
    @stepofori So you have debugged your code and seen that the Claims contain the Roles claim but you have not seen where the NullRefrenceException occurs while doing that? – Ralf Jan 12 '23 at 12:46
  • [Tutorial: Learn to debug C# code using Visual Studio](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger). – Olivier Jacot-Descombes Jan 12 '23 at 12:56
  • @Ralf var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, _configuration["JwtConfig:Subject"]), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()), new Claim("Email", user.Email.ToString()), new Claim("Password", user.Password.ToString()), new Claim("Role", role.ToString()), – step ofori Jan 12 '23 at 13:04
  • @stepofori there are presumably a gazillion things happening between the code you show in this comment that creates the claims and reaching the code you show in your question that needs the claim. You need to find out if it reaches the code in question. And the tool checking it is debugging. – Ralf Jan 12 '23 at 13:07

1 Answers1

0

i have found the answer... this line was looking for a claimtype Role

var role = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Role).Value;

so i change how claims syntax was written to include the claimtype

 new Claim(ClaimTypes.Role, role.ToString()),
step ofori
  • 19
  • 4