.NET CORE使用JWT用户验证方案

 

JwtHelper.cs

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace WhoAmI.Api.Common
{
    public static class JwtHelper
    {
        public static string GeneratorToken()
        {
            var secret = ConfigHelper.GetConfig("JWTSetting:Secret");
            var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "") };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: "www.zhibin.org",
                audience: "wechat",
                claims: claims,
                expires: DateTime.Now.AddMinutes(60),
                signingCredentials: creds);
            return new JwtSecurityTokenHandler().WriteToken(token);

        }
    }
}

Program.cs


#region 添加校验
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.Events = new JwtBearerEvents()
    {
        OnMessageReceived = context =>
        {
            context.Token = context.Request.Headers["X-Token"];
            return Task.CompletedTask;
        }
    };
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "www.zhibin.org",
        ValidAudience = "wechat",
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetValue<string>("JWTSetting:Secret"))),
};
});
#endregion 

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JWTSetting": {
    "Secret": "zVH3Fo1vvhqgG4fgu9Twugx6gPce89UQrFs"
  } 
}

如何使用?


        public IActionResult XcxLogin(string code)
        {
            var u = new User(1);
            ResultModel result = new ResultModel();
            var r = WechatApi.OnLogin(code);
            if (r.Success)
            {
                var sb = (dynamic)r.Data;
                var user = WhoAmI.Logic.User.getByOpenId(sb.openId, Platform.微信小程序);
               
                result.Success = true;
                result.Data = new { uid=user.Id, openid = sb.openId ,token=Common.JwtHelper.GeneratorToken()};//将令牌返回客户端
            }
            else
            {
                result.Message = r.Message;
            }
            return Json(result);
        }

客户端接收到token,保存到本地cookie或者local storage,请求时,向请求头添加X-Token字段,将服务端保存的token传递回去

'X-Token':usr.token

发表回复

您的电子邮箱地址不会被公开。