Reza Del
Reza Del

Reputation: 793

Jwt Code not working on .NET Core 2

I am trying to learn how to Use add Jwt to an API that i am working on. I have followed up this introduction on how to build an API with Jwt. My application now does generate the Jwt Code but when i call Authorize section of the API, with the Authorization header and Bearer using post man i am getting 401 Unauthrized respond. my Code is

StattUp.cs

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.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        /**/
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
        app.UseAuthentication();

    }
}

TokenController.cs

public class TokenController : Controller
{
    private IConfiguration _config;
    public TokenController (IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult CreateToken (LoginModel login)
    {
        IActionResult response = Unauthorized();
        var user = Authenticate(login); 
        if (user != null)
        {
            var tokenString = BuildToken(user);
            response = Ok(new {token = tokenString });
        }
        return response;
    }
    private string BuildToken (UserModel user)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
            _config["Jwt:Issuer"],
            expires: DateTime.Now.AddHours(30),
            signingCredentials: creds
            );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    private UserModel Authenticate(LoginModel login)
    {
        UserModel user = null;
        if (login.Username != null && login.Password != null)
        {
            if (login.Username.ToLower() == "r" && login.Password.ToLower() == "d")
            {
                user = new UserModel { Name = "R D", Email = "[email protected]" };

            }
        }
        return user;
    }









    public class LoginModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    private class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime Birthdate { get; set; }
    }

}

BooksController.cs

 public class BooksController : Controller
{
    [HttpGet, Authorize]
    public IEnumerable<Book> Get()
    {
        var currentUser = HttpContext.User;
        var result = new Book[] {
                new Book { Author = "Ray Bradbury",Title = "Fahrenheit 451" },
                new Book { Author = "Gabriel García Márquez", Title = "One Hundred years of Solitude" },
                new Book { Author = "George Orwell", Title = "1984" },
                new Book { Author = "Anais Nin", Title = "Delta of Venus" , AgeRestriction = true}

        };
        return result; 
    }
}

public class Book
{

    public string Author { get; set; }
    public string Title { get; set; }
    public bool AgeRestriction { get; set; }
}

Appsetting.json

  {
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "Jwt": {
    "Key": "veryVerySecretKey",
    "Issuer": "http://localhost:50431/"
  }
}

P.S I have tried call the http://localhost:50431/api/books using Postman with

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjE1NzgxMTgsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTA0MzEvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1MDQzMS8ifQ.D4o7ruHv4d6QFKQvOFTmtKwlbIgvTF-PnYJXUdaRCg8

and i have not luck so any help would be appreciate

Upvotes: 2

Views: 1667

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

This is a very common mistake. You should add authentication middleware before MVC middleware. The order really matters here.

So to fix the problem change Startup.Configure method in the following way:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication();
    app.UseMvc();
}

Check following articles for more details:

Upvotes: 6

Related Questions