如何在Asp .Net客户端中使用Jwt处理身份验证和授权

时间:2019-03-26 10:42:44

标签: c# authentication asp.net-core jwt asp.net-core-webapi

您好,我正在努力了解如何在工作中使用Jwt实现Web Api。我希望用户仅使用Api进行一次身份验证,并获得一个令牌,供他们在我们Intranet中的所有应用程序之间使用。

Web Api可以工作,当我使用邮递员时,可以使用身份验证令牌从中检索信息

enter image description here

这是我的登录控制器

[Route("api/[controller]")]
[ApiController]
public class LoginController : Controller
{
    private IConfiguration _config;

    public LoginController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Login([FromBody] UserViewModel login)
    {
        IActionResult response = Unauthorized();
        var user = AuthenticateUser(login);

        if (user != null)
        {
            var tokenString = GenerateJSONWebToken(user);
            response = Ok(new { token = tokenString });
        }

        return response;
    }

    private string GenerateJSONWebToken(UserViewModel userInfo)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new[] {
            new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),
            new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
            new Claim("DateOfJoin", userInfo.DateOfJoin.ToString("yyyy-MM-dd")),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())   
        };

        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          null,
          expires: DateTime.Now.AddMinutes(120),
          signingCredentials: credentials);

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

    private UserViewModel AuthenticateUser(UserViewModel login)
    {
        UserViewModel user = null;

        // Validate the User Credentials    
        if (login.Username == "test")
        {
            user = new UserViewModel { Username = "test", Nome = "test", Email = "test@test.com" };
        }

        return user;
    }

    [HttpGet]
    [Authorize]
    public ActionResult<IEnumerable<string>> Get()
    {
        var currentUser = HttpContext.User;
        int spendingTimeWithCompany = 0;

        if (currentUser.HasClaim(c => c.Type == "DateOfJoin"))
        {
            DateTime date = DateTime.Parse(currentUser.Claims.FirstOrDefault(c => c.Type == "DateOfJoin").Value);
            spendingTimeWithCompany = DateTime.Today.Year - date.Year;
        }

        if (spendingTimeWithCompany > 5)
        {
            return new string[] { "High Time1", "High Time2", "High Time3", "High Time4", "High Time5" };
        }
        else
        {
            return new string[] { "value1", "value2", "value3", "value4", "value5" };
        }
    }
}

现在我的问题是,我试图了解当客户需要输入应用程序并使用它时,如何处理这些客户。

  1. 所有应用程序都具有受限访问权限,并被重定向到Web API前端进行登录。
  2. 用户名和密码发送到Web API。
  3. 使用访问目录验证凭据
  4. 如果验证通过声明成功,则返回Jwt令牌。

现在的问题是...

我实际上如何在客户端上访问此令牌并获得索赔?

例如,假设我有一个MVC客户端,并且用户正在尝试访问需要管理员声明授权的页面。我现在该怎么办?我不知道我是否可以通过HttpContext访问声明,还是必须做一些事情来检测每个客户端上的Jwt令牌。

0 个答案:

没有答案
相关问题