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.
haknook is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.