本文介绍了在.net核心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服务器数据库

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核心Web API中将JWT令牌存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:52