在 .net core web api 中存储 JWT 令牌的位置? [英] Where to store JWT Token in .net core web api?

查看:65
本文介绍了在 .net core web api 中存储 JWT 令牌的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 web api 访问数据,我想对 web api 进行身份验证和授权.为此,我正在使用 JWT 令牌身份验证.但我不知道应该在哪里存储访问令牌?

I am using web api for accessing data and I want to authenticate and authorize web api.For that I am using JWT token authentication. But I have no idea where should I store access tokens?

我想做什么?

1)登录后存储令牌

2)如果用户想访问web api的任何方法,请检查此用户的令牌是否有效,如果有效则授予访问权限.

2)if user want to access any method of web api, check the token is valid for this user,if valid then give access.

我知道两种方法

1) 使用 cookie

1)using cookies

2)sql server 数据库

2)sql server database

从上面存储令牌的更好方法是哪一种?

which one is the better way to store tokens from above?

推荐答案

或者,如果您只是想使用 JWT 进行身份验证,则实现会略有不同

Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = context =>
        {
            var user = context.Principal.Identity.Name;
            //Grab the http context user and validate the things you need to
            //if you are not satisfied with the validation fail the request using the below commented code
            //context.Fail("Unauthorized");
            
            //otherwise succeed the request
            return Task.CompletedTask;
        }
    };
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
        ValidateIssuer = false,
        ValidateAudience = false

    };
});

在使用MVC之前仍然应用使用身份验证.

still applying use authentication before use MVC.

[请注意这些是非常简单的示例,您可能需要进一步加强安全性并实施最佳实践,例如使用强密钥、可能从环境加载配置等]

[Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]

然后实际的身份验证操作,比如在 AuthenticationController 中可能是这样的

Then the actual authentication action, say perhaps in AuthenticationController would be something like

[Route("api/[controller]")]
[Authorize]
public class AuthenticationController : Controller
{
    [HttpPost("authenticate")]
    [AllowAnonymous]
    public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
    {
        //LoginRequest may have any number of fields expected .i.e. username and password

        //validate user credentials and if they fail return
        //return Unauthorized();

        var claimsIdentity = new ClaimsIdentity(new Claim[]
           {
            //add relevant user claims if any
           }, "Cookies");

        var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
        await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
        return Ok();
    }
}

在本例中,我使用 cookie,因此我使用 Set Cookie 返回 HTTP 结果.如果我使用 JWT,我会返回类似

in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like

[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
{
    //validate user credentials and if they validation failed return a similar response to below
    //return NotFound();

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            //add my users claims etc
        }),
        Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
        Issuer = "YourOrganizationOrUniqueKey",
        IssuedAt = DateTime.UtcNow
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
    var cookieOptions = new CookieOptions();
    cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation 
    cookieOptions.Domain = Request.Host.Value;
    cookieOptions.Path = "/";
    Response.Cookies.Append("jwt", tokenString, cookieOptions);
    return Ok();
}

这篇关于在 .net core web api 中存储 JWT 令牌的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆