C#/.NET 微服务专题(JWT的权限认证使用)

JWT客户端的使用

安装:Microsoft.AspNetCore.Authentication.JwtBearer

public void ConfigureServices(IServiceCollection services)
{
    #region jwt校验
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,//是否验证Issuer
            ValidateAudience = true,//是否验证Audience
            ValidateLifetime = true,//是否验证失效时间
            ValidateIssuerSigningKey = true,//是否验证SecurityKey
            ValidAudience = this.Configuration["audience"],//Audience
            ValidIssuer = this.Configuration["issuer"],//Issuer,这两项和前面签发jwt的设置一致
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["SecurityKey"])),//拿到SecurityKey
            //AudienceValidator = (m, n, z) =>
            //{
            //    return m != null && m.FirstOrDefault().Equals(this.Configuration["audience"]);
            //},//自定义校验规则,可以新登录后将之前的无效
        };
    });
    #endregion
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    #region jwt
    app.UseAuthentication();//注意添加这一句,启用验证
    #endregion
}

配置文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "JDDbConnection": "Server=ElevenPC;Database=advanced11;User id=sa;password=Passw0rd",
    "Write": "Data Source=ElevenPC; Database=Customers; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
    "Read": [
      "Data Source=.; Database=Customers_New1; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
      "Data Source=XTPC; Database=Customers_New2; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
      "Data Source=.; Database=Customers_New3; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True"
    ]
  },
  "audience": "http://localhost:5726",
  "issuer": "http://localhost:5726",
  "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
}

使用

[Route("api/[controller]/[action]")]
[ApiController]
[Microsoft.AspNetCore.Authorization.Authorize]
public class UsersNewController : ControllerBase
{
    #region HttpGet
    // GET api/Users/5
    [HttpGet]
    [Microsoft.AspNetCore.Authorization.AllowAnonymous]
    public Users GetUserByID(int id)
    {
        base.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");//允许跨域
    }
    #endregion HttpPost
}

JWT服务端的使用

安装:System.IdentityModel.Tokens.Jwt

[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
    #region MyRegion
    private ILogger<AuthenticationController> _logger = null;
    private IJWTService _iJWTService = null;
    private readonly IConfiguration _iConfiguration;
    public AuthenticationController(ILoggerFactory factory,
        ILogger<AuthenticationController> logger,
        IConfiguration configuration
        , IJWTService service)
    {
        this._logger = logger;
        this._iConfiguration = configuration;
        this._iJWTService = service;
    }
    #endregion
    [Route("Get")]
    [HttpGet]
    public IEnumerable<int> Get()
    {
        return new List<int>() { 1, 2, 3, 4, 6, 7 };
    }

    [Route("Login")]
    [HttpPost]
    public string Login(string name, string password)
    {
        if ("Eleven".Equals(name) && "123456".Equals(password))//应该数据库
        {
            string token = this._iJWTService.GetToken(name);
            return JsonConvert.SerializeObject(new
            {
                result = true,
                token
            });
        }
        else
        {
            return JsonConvert.SerializeObject(new
            {
                result = false,
                token = ""
            });
        }
    }
}
public interface IJWTService
{
    string GetToken(string UserName);
}

public class JWTService : IJWTService
{
    private readonly IConfiguration _configuration;
    public JWTService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string GetToken(string UserName)
    {
        var claims = new[]
        {
           new Claim(ClaimTypes.Name, UserName),
           new Claim("NickName","XT"),
           new Claim("Role","Administrator"),//传递其他信息  
        };
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        /**
         * Claims (Payload)
            Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:

            iss: The issuer of the token,token 是给谁的
            sub: The subject of the token,token 主题
            exp: Expiration Time。 token 过期时间,Unix 时间戳格式
            iat: Issued At。 token 创建时间, Unix 时间戳格式
            jti: JWT ID。针对当前 token 的唯一标识
            除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
         * */
        var token = new JwtSecurityToken(
            issuer: _configuration["issuer"],
            audience: _configuration["audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(5),//5分钟有效期
            signingCredentials: creds);
        string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
        return returnToken;
    }
}
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页