how to use jwt to obtain the info of the currently logged in user?

I’m working on a web app using vuejs and asp.net. I’m trying to sign in a custom identity user and send back a token back to the client to user to get all the info of the current logged in user, but when i send the request to fetch the info i’m always unauthorized.
below are the program.cs, the custom identity user and the controller for the custom identity user and the client side to send the request to fetch the info:

using JobHosting.Models;
using JobHosting.Models.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;

// Jwt Configuration
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
  x.TokenValidationParameters = new TokenValidationParameters
  {
      ValidIssuer = config["JwtSettings:Issuer"],
      ValidAudience = config["JwtSettings:Audience"],
      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JwtSettings:Key"])),
      ValidateIssuer = true,
      ValidateAudience = true,
      ValidateLifetime = true,
      ValidateIssuerSigningKey = true
  };
});

builder.Services.AddAuthorization();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped<IJobListingRepository, JobListingRepository>();

builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection"));
});

builder.Services.AddIdentity<UserAccount, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
builder.Services.Configure<IdentityOptions>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
});

builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
    policy =>
    {
        policy.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .WithOrigins("http://localhost:8080");
    }
);
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseCors();

app.UseHttpsRedirection();

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

app.MapControllers();
app.Run();

using Microsoft.AspNetCore.Identity;

namespace JobHosting.Models
{
public class UserAccount : IdentityUser
{
    public string Password { get; set; } = string.Empty;
    public string UserType { get; set; } = string.Empty;
    public string JHFullName { get; set; } = string.Empty;
    public string JHResume { get; set; } = string.Empty;
    public String JListerName { get; set; } = string.Empty;
    public String JListerWebsite { get; set; } = string.Empty ;
    public List<int> Listings { get; set; } = new List<int>();

    public UserAccount(string Email, string UserName, string UserType)
    {
        this.Email = Email;
        this.UserName = UserName;
        this.UserType = UserType;
    }
    
    override
    public String ToString()
    {
        return Id + " " + UserName + " " + UserType + " " + Email + " ";
    }
    }
}

using JobHosting.Models;
using JobHosting.Models.Repositories;
using JobHosting.Models.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JobHosting.Controllers
{
[Route("api/Authentication")]
[ApiController]
[AllowAnonymous]
public class UserAccountsController : Controller
{
    private readonly UserManager<UserAccount> jobHuntingUM;
    private readonly SignInManager<UserAccount> jobHuntingSM;
    private readonly IConfiguration configuration;
    public UserAccountsController(UserManager<UserAccount> jobHuntingUM, SignInManager<UserAccount> jobHuntingSM, IConfiguration configuration)
    {
        this.jobHuntingSM = jobHuntingSM;
        this.jobHuntingUM = jobHuntingUM;
        this.configuration = configuration;
    }

    [HttpPost("SignUp")]
    public async Task<ActionResult<UserAccount>> SignUp([FromBody]SignUpViewModel model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if(await jobHuntingUM.FindByEmailAsync(model.Email) == null) {
                    UserAccount user = new (model.Email, model.UserName, model.UserType);
                    Console.WriteLine(user.Email+" "+user.UserName+" "+user.UserType+" "+model.Password+" "+user.Password);
                    var res = await jobHuntingUM.CreateAsync(user, model.Password);
                    if (res.Succeeded)
                    {
                        await jobHuntingSM.SignInAsync(user, isPersistent: false);
                        return StatusCode(StatusCodes.Status200OK, "SignUp successfull, you have been signed in");
                    }
                    else
                    {
                        var errors = "";
                        foreach(var error in res.Errors)
                        {
                            errors += error.Description;
                        }
                        return StatusCode(StatusCodes.Status500InternalServerError, errors);// $"An error has occured while creating the new user {errors}");
                    }
                }
                else {
                    return StatusCode(StatusCodes.Status409Conflict, "User with that email already exists");
                }
            }
            else
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "invalid input data");
            }
        }
        catch(Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpPost("SignOut")]
    [Authorize]
    public async Task<ActionResult<UserAccount>> Logout()
    {
        await jobHuntingSM.SignOutAsync();
        return null;
    }

    [HttpPost("SignIn")]
    public async Task<ActionResult<UserAccount>> SignIn([FromBody] LoginViewModel model)
    {
        try {
            if(ModelState.IsValid)
            {
                var user = await jobHuntingUM.FindByNameAsync(model.UserName);
                if (user == null || !await jobHuntingUM.CheckPasswordAsync(user, model.Password))
                {
                    return BadRequest("Wrong username or password");
                }
                var res = await jobHuntingSM.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);
                if(res.Succeeded)
                {
                    var claims = new List<Claim>
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Email, user.Email),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:key"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                        issuer: configuration["JwtSettings:Issuer"],
                        audience: configuration["JwtSettings:Issuer"],
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(30),
                        signingCredentials: creds
                    );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
                    return Ok(new { token = tokenString });
                }
                else {
                    return Unauthorized("invalid login attempt");
                }
            }
        }catch(Exception e) {
            return BadRequest($"error {e.Message}");
        }

        return null;
    }

    [HttpGet("Info")]
    //[Authorize]
    public ActionResult<UserAccount> GetCurrentUser()
    {
        try
        {
            var email = User.FindFirstValue(ClaimTypes.Email);
            var userName = User.FindFirstValue(ClaimTypes.Name);


            foreach (var claim in User.Claims)
            {
                Console.WriteLine("*");
                Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
            }

            if (email == null || userName == null) { 
                return Unauthorized();
            }
            return Ok(
                new
                {
                    Email = email,
                    UserName = userName
                }    
            );
        }
        catch(Exception e)
        {
            return BadRequest(e.Message);
        }
    }

}
}


<script>
import axios from 'axios';
import { useRoute } from 'vue-router';
import { onMounted, ref } from 'vue';
export default {
    name: "UserSettingsView",
    setup() {
        const route = useRoute()
        const token = route.params.token;
        const userData = ref({})
        onMounted(() => {
            console.log(token)
            axios.get("https://localhost:7075/api/Authentication/Info",
                {
                    headers: {
                        "Authorization": `Bearer ${token}`
                    }
                }
            )
            .then(response => userData.value = response.data)
            .catch(err => console.log(err))
        })
        return {
            token,
            userData
        }
    }
}
</script>
<template>
<!--This is a placeholder for what is to come-->
{{ userData }}
<h1>User info</h1>
<form>
    <div class="mb-3">
        <label class="form-label">Email</label>
        <input type="Text" class="form-control" v-model="userData.email" placeholder="name example">
    </div>
    <div class="mb-3">
        <label class="form-label">IsEmailConfirmed</label>
        <input type="text" class="form-control" v-model="userData.isEmailConfirmed" placeholder="Expiration date">
    </div>
</form>
</template>

i tried sending the bearer token in the header of the request and that didn’t work and honestly that’s about as deep as my understanding of how that should work goes.

New contributor

haknook is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật