C# API Gives error 401 in postaman, even when using the generated token

Viewed 44

I have a api endpoints that allows me to login. Then I have a other api endpoint where I want to get data from.

Here is a exemple of data that I want to get from my postman As you can see when I use the login endpoint I get a token

Login

Then I want to use the token to get the clients but it does not work I get A 401 here is a image of the problem. As you can see I have used the token but I am still not authorized why is that? Thank you for your help.

Get Client

I have the following Controller to authenticate.

[Route("api/auth")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly ILogger<AuthController> _logger;
    private readonly IEmployeeService _employeeService;

    public AuthController(ILogger<AuthController> logger, IEmployeeService employeeService)
    {
        _logger = logger;
        _employeeService = employeeService;
    }


    [HttpPost, Route("login")]
    public IActionResult Login([FromBody] LoginModel user)
    {
       Employee employeeFromDB = Task.Run(async () => await _employeeService.GetByUserName(user.UserName)).Result;

        if (user == null)
        {
            return BadRequest("Invalid client request");
        }

        if(employeeFromDB == null) 
        {
            return Unauthorized();
        } 
        else if (user.UserName == employeeFromDB.UserName && user.Password == "123qwe")
        {
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@45"));
            var signingCreditials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var tokenOptions = new JwtSecurityToken(
                issuer: "https://localhost:44363/",
                audience: "https://localhost:44363/",
                claims: new List<Claim>(),
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: signingCreditials
                );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);

            return Ok(new { Token = tokenString });
        }

        return Unauthorized();
    }

I have the following controller that is secured

    [Route("api/[controller]")]
    [ApiController]
    public class ClientsController : ControllerBase
    {
        private readonly ILogger<ClientsController> _logger;
        private readonly IClientService _clientService;

        public ClientsController(ILogger<ClientsController> logger, IClientService clientService)
        {
            _logger = logger;
            _clientService = clientService;
        }

        // GET api/clients
        [HttpGet]
        [Authorize]
        public IEnumerable<ClientViewModel> Get()
        {
            ClientViewModel clientViewModel;
            List<ClientViewModel> listClientViewModels = new List<ClientViewModel>();

            var clients = Task.Run(async () => await _clientService.GetAllClients()).Result;

            foreach (var client in clients) 
            {
                clientViewModel = new ClientViewModel();
                clientViewModel.ClientId = client.ClientId;
                clientViewModel.Active = client.Active;
                clientViewModel.Address = client.Address;
                clientViewModel.City = client.City;
                clientViewModel.ClienteName = client.ClienteName;
                clientViewModel.ComercialEmployeeId = client.ComercialEmployeeId;
                clientViewModel.Confirmed = client.Confirmed;
                clientViewModel.CountryId = client.CountryId;
                clientViewModel.CreationDate = client.CreationDate;
                clientViewModel.DANE = client.DANE;
                clientViewModel.Department = client.Department;
                clientViewModel.ElectronicBillingEmail = client.ElectronicBillingEmail;
                clientViewModel.Eliminated = client.Eliminated;
                clientViewModel.NIT = client.NIT;
                clientViewModel.PostalCode = client.PostalCode;
                clientViewModel.Phone = client.Phone;

                listClientViewModels.Add(clientViewModel);
            }

            return listClientViewModels;
        }
   }
}

Here is my startup code

public class Startup
{
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("EnableCORS", builder => 
        {
            builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
        });
    });

    services.AddAuthentication(opt =>
    {
        opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(opttions =>
    {

        opttions.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,

            ValidIssuer = "https://localhost:44363",
            ValidAudience = "https://localhost:44363",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@45"))
        };
    });

    services.AddControllersWithViews();
   
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
    
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<DatabaseMigrator>();
    services.AddDbContext<erp_colombiaDbContext>(options => options.UseMySql(
             Configuration.GetConnectionString("DefaultConnection"),
             optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName)));

    services.AddDbContext<erp_colombiaDbContext>(options => options.UseMySql(
            Configuration.GetConnectionString("DefaultConnection"),
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName)));
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseCors("EnableCORS");

    app.UseStaticFiles();
    if (!env.IsDevelopment())
    {
        app.UseSpaStaticFiles();
    }

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }
    });
}
0 Answers
Related