JWT on .NET Core 2.0

后端 未结 6 1931
忘掉有多难
忘掉有多难 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: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 options) : base(options)
        {
            this.Database.EnsureCreated();
        }
    
        public DbSet 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 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 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.

提交回复
热议问题