JWT on .NET Core 2.0

后端 未结 6 1851
忘掉有多难
忘掉有多难 2020-11-28 18:27

I\'ve been on quite an adventure to get JWT working on DotNet core 2.0 (now reaching final release today). There is a ton of documentation, but all the sample code

相关标签:
6条回答
  • 2020-11-28 19:00

    Here is my implementation for a .Net Core 2.0 API:

        public IConfigurationRoot Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services
            services.AddMvc(
            config =>
            {
                // This enables the AuthorizeFilter on all endpoints
                var policy = new AuthorizationPolicyBuilder()
                                    .RequireAuthenticatedUser()
                                    .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
                
            }
            ).AddJsonOptions(opt =>
            {
                opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });
    
            services.AddLogging();
    
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Audience = Configuration["AzureAD:Audience"];  
                options.Authority = Configuration["AzureAD:AADInstance"] + Configuration["AzureAD:TenantId"];
            });            
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseAuthentication(); // THIS METHOD MUST COME BEFORE UseMvc...() !!
            app.UseMvcWithDefaultRoute();            
        }
    

    appsettings.json:

    {
      "AzureAD": {
        "AADInstance": "https://login.microsoftonline.com/",
        "Audience": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "Domain": "mydomain.com",
        "TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      },
      ...
    }
    

    The above code enables auth on all controllers. To allow anonymous access you can decorate an entire controller:

    [Route("api/[controller]")]
    [AllowAnonymous]
    public class AnonymousController : Controller
    {
        ...
    }
    

    or just decorate a method to allow a single endpoint:

        [AllowAnonymous]
        [HttpPost("anonymousmethod")]
        public async Task<IActionResult> MyAnonymousMethod()
        {
            ...
        }
    

    Notes:

    • This is my first attempt at AD auth - if anything is wrong, please let me know!

    • Audience must match the Resource ID requested by the client. In our case our client (an Angular web app) was registered separately in Azure AD, and it used its Client Id, which we registered as the Audience in the API

    • ClientId is called Application ID in the Azure Portal (why??), the Application ID of the app registration for the API.

    • TenantId is called Directory ID in the Azure Portal (why??), found under Azure Active Directory > Properties

    • If deploying the API as an Azure hosted Web App, ensure you set the Application Settings:

      eg. AzureAD:Audience / xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

    0 讨论(0)
  • 2020-11-28 19:06

    Here is a full working minimal sample with a controller. I hope you can check it using Postman or JavaScript call.

    1. appsettings.json, appsettings.Development.json. Add a section. Note, Key should be rather long and Issuer is an address of the service:

      ...
      ,"Tokens": {
          "Key": "Rather_very_long_key",
          "Issuer": "http://localhost:56268/"
      }
      ...
      

      !!! In real project, don't keep Key in appsettings.json file. It should be kept in Environment variable and take it like this:

      Environment.GetEnvironmentVariable("JWT_KEY");
      

    UPDATE: Seeing how .net core settings work, you don't need to take it exactly from Environment. You may use setting. However,instead we may write this variable to environment variables in production, then our code will prefer environment variables instead of configuration.

    1. AuthRequest.cs : Dto keeping values for passing login and password:

      public class AuthRequest
      {
          public string UserName { get; set; }
          public string Password { get; set; }
      }
      
    2. Startup.cs in Configure() method BEFORE app.UseMvc() :

      app.UseAuthentication();
      
    3. Startup.cs in ConfigureServices() :

      services.AddAuthentication()
          .AddJwtBearer(cfg =>
          {
              cfg.RequireHttpsMetadata = false;
              cfg.SaveToken = true;
      
              cfg.TokenValidationParameters = new TokenValidationParameters()
              {
                  ValidIssuer = Configuration["Tokens:Issuer"],
                  ValidAudience = Configuration["Tokens:Issuer"],
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
              };
      
          });
      
    4. Add a controller:

          [Route("api/[controller]")]
          public class TokenController : Controller
          {
              private readonly IConfiguration _config;
              private readonly IUserManager _userManager;
      
              public TokenController(IConfiguration configuration, IUserManager userManager)
              {
                  _config = configuration;
                  _userManager = userManager;
              }
      
              [HttpPost("")]
              [AllowAnonymous]
              public IActionResult Login([FromBody] AuthRequest authUserRequest)
              {
                  var user = _userManager.FindByEmail(model.UserName);
      
                  if (user != null)
                  {
                      var checkPwd = _signInManager.CheckPasswordSignIn(user, model.authUserRequest);
                      if (checkPwd)
                      {
                          var claims = new[]
                          {
                              new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                              new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
                          };
      
                          var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                          var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
      
                          var token = new JwtSecurityToken(_config["Tokens:Issuer"],
                          _config["Tokens:Issuer"],
                          claims,
                          expires: DateTime.Now.AddMinutes(30),
                          signingCredentials: creds);
      
                          return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
                      }
                  }
      
                  return BadRequest("Could not create token");
              }}
      

    That's all folks! Cheers!

    UPDATE: People ask how get Current User. Todo:

    1. In Startup.cs in ConfigureServices() add

      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
      
    2. In a controller add to constructor:

      private readonly int _currentUser;
      public MyController(IHttpContextAccessor httpContextAccessor)
      {
         _currentUser = httpContextAccessor.CurrentUser();
      }
      
    3. Add somewhere an extension and use it in your Controller (using ....)

      public static class IHttpContextAccessorExtension
      {
          public static int CurrentUser(this IHttpContextAccessor httpContextAccessor)
          {
              var stringId = httpContextAccessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
              int.TryParse(stringId ?? "0", out int userId);
      
              return userId;
          }
      }
      
    0 讨论(0)
  • 2020-11-28 19:11

    Asp.net Core 2.0 JWT Bearer Token Authentication Implementation with Web Api Demo

    Add Package "Microsoft.AspNetCore.Authentication.JwtBearer"

    Startup.cs ConfigureServices()

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
    
                    cfg.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = "me",
                        ValidAudience = "you",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")) //Secret
                    };
    
                });
    

    Startup.cs Configure()

    // ===== Use Authentication ======
            app.UseAuthentication();
    

    User.cs // It is a model class just for example. It can be anything.

    public class User
    {
        public Int32 Id { get; set; }
        public string Username { get; set; }
        public string Country { get; set; }
        public string Password { get; set; }
    }
    

    UserContext.cs // It is just context class. It can be anything.

    public class UserContext : DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options)
        {
            this.Database.EnsureCreated();
        }
    
        public DbSet<User> Users { get; set; }
    }
    

    AccountController.cs

    [Route("[controller]")]
    public class AccountController : Controller
    {
    
        private readonly UserContext _context;
    
        public AccountController(UserContext context)
        {
            _context = context;
        }
    
        [AllowAnonymous]
        [Route("api/token")]
        [HttpPost]
        public async Task<IActionResult> Token([FromBody]User user)
        {
            if (!ModelState.IsValid) return BadRequest("Token failed to generate");
            var userIdentified = _context.Users.FirstOrDefault(u => u.Username == user.Username);
                if (userIdentified == null)
                {
                    return Unauthorized();
                }
                user = userIdentified;
    
            //Add Claims
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, "data"),
                new Claim(JwtRegisteredClaimNames.Sub, "data"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };
    
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")); //Secret
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
            var token = new JwtSecurityToken("me",
                "you",
                claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);
    
            return Ok(new
            {
                access_token = new JwtSecurityTokenHandler().WriteToken(token),
                expires_in = DateTime.Now.AddMinutes(30),
                token_type = "bearer"
            });
        }
    }
    

    UserController.cs

    [Authorize]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly UserContext _context;
    
        public UserController(UserContext context)
        {
            _context = context;
            if(_context.Users.Count() == 0 )
            {
                _context.Users.Add(new User { Id = 0, Username = "Abdul Hameed Abdul Sattar", Country = "Indian", Password = "123456" });
                _context.SaveChanges();
            }
        }
    
        [HttpGet("[action]")]
        public IEnumerable<User> GetList()
        {
            return _context.Users.ToList();
        }
    
        [HttpGet("[action]/{id}", Name = "GetUser")]
        public IActionResult GetById(long id)
        {
            var user = _context.Users.FirstOrDefault(u => u.Id == id);
            if(user == null)
            {
                return NotFound();
            }
            return new ObjectResult(user);
        }
    
    
        [HttpPost("[action]")]
        public IActionResult Create([FromBody] User user)
        {
            if(user == null)
            {
                return BadRequest();
            }
    
            _context.Users.Add(user);
            _context.SaveChanges();
    
            return CreatedAtRoute("GetUser", new { id = user.Id }, user);
    
        }
    
        [HttpPut("[action]/{id}")]
        public IActionResult Update(long id, [FromBody] User user)
        {
            if (user == null)
            {
                return BadRequest();
            }
    
            var userIdentified = _context.Users.FirstOrDefault(u => u.Id == id);
            if (userIdentified == null)
            {
                return NotFound();
            }
    
            userIdentified.Country = user.Country;
            userIdentified.Username = user.Username;
    
            _context.Users.Update(userIdentified);
            _context.SaveChanges();
            return new NoContentResult();
        }
    
    
        [HttpDelete("[action]/{id}")]
        public IActionResult Delete(long id)
        {
            var user = _context.Users.FirstOrDefault(u => u.Id == id);
            if (user == null)
            {
                return NotFound();
            }
    
            _context.Users.Remove(user);
            _context.SaveChanges();
    
            return new NoContentResult();
        }
    }
    

    Test on PostMan:

    Pass TokenType and AccessToken in Header in other webservices.

    Best of Luck! I am just Beginner. I only spent one week to start learning asp.net core.

    0 讨论(0)
  • 2020-11-28 19:16

    Here is a solution for you.

    In your startup.cs, firstly, config it as services:

      services.AddAuthentication().AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken = true;
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey = "somethong",
                    ValidAudience = "something",
                    :
                };
            });
    

    second, call this services in config

              app.UseAuthentication();
    

    now you can use it in your controller by add attribute

              [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
              [HttpGet]
              public IActionResult GetUserInfo()
              {
    

    For full details source code that use angular as Frond-end see here

    0 讨论(0)
  • 2020-11-28 19:23

    Just to update on the excellent answer by @alerya I had to modify the helper class to look like this;

    public static class IHttpContextAccessorExtension
        {
            public static string CurrentUser(this IHttpContextAccessor httpContextAccessor)
            {           
                var userId = httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; 
                return userId;
            }
        }
    

    Then I could obtain the userId in my service layer. I know it's easy in the controller, but a challenge further down.

    0 讨论(0)
  • My tokenValidationParameters works when they look like this:

     var tokenValidationParameters = new TokenValidationParameters
      {
          ValidateIssuerSigningKey = true,
          IssuerSigningKey = GetSignInKey(),
          ValidateIssuer = true,
          ValidIssuer = GetIssuer(),
          ValidateAudience = true,
          ValidAudience = GetAudience(),
          ValidateLifetime = true,
          ClockSkew = TimeSpan.Zero
       };
    

    and

        static private SymmetricSecurityKey GetSignInKey()
        {
            const string secretKey = "very_long_very_secret_secret";
            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
    
            return signingKey;
        }
    
        static private string GetIssuer()
        {
            return "issuer";
        }
    
        static private string GetAudience()
        {
            return "audience";
        }
    

    Moreover, add options.RequireHttpsMetadata = false like this:

             .AddJwtBearer(options =>
           {         
               options.TokenValidationParameters =tokenValidationParameters         
               options.RequireHttpsMetadata = false;
           });
    

    EDIT:

    Dont forget to call

     app.UseAuthentication();
    

    in Startup.cs -> Configure method before app.UseMvc();

    0 讨论(0)
提交回复
热议问题