Exemplo n.º 1
0
        private async Task AttachAccount(HttpContext context, JwtDbContext dataContext, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_config.GetSection("JwtKey").Value);

                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    //Set ClockKew = 0 để thông báo token đã hết hạn
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);
                var jwtToken = (JwtSecurityToken)validatedToken;

                int.TryParse(jwtToken.Claims.First(x => x.Type == "id").Value, out int accountId);

                var id = await dataContext.Users.FindAsync(accountId);

                if (String.Equals(JWTHelpers.ValidateJwtToken(token, key), id.Id.ToString()))
                {
                    context.Items["Account"] = await dataContext.Users.FindAsync(accountId);
                }
            }
            catch
            {
                //do nothing
            }
        }
        public IActionResult Login(int id)
        {
            var u      = _db.Users.Find(id);
            var strKey = _config.GetSection("JwtKey").Value;
            var key    = Encoding.ASCII.GetBytes(strKey);
            var tk     = JWTHelpers.GenerationToken(u.Id, key);

            return(Ok(new {
                user = u,
                token = "Bear " + tk
            }));
        }
Exemplo n.º 3
0
 public Startup(IConfiguration configuration, IHostingEnvironment _env)
 {
     Configuration   = configuration;
     this._env       = _env;
     this.jwtHelpers = new JWTHelpers();
 }