加入收藏 | 设为首页 | 会员中心 | 我要投稿 惠州站长网 (https://www.0752zz.com.cn/)- 办公协同、云通信、物联设备、操作系统、高性能计算!
当前位置: 首页 > 站长百科 > 正文

ASP.NET Core使用JWT认证授权的方法

发布时间:2020-11-23 22:09:57 所属栏目:站长百科 来源:网络整理
导读:副标题#e# 短视频,自媒体,达人种草一站服务 这篇文章主要介绍了ASP.NET Core使用JWT认证授权的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 demo地址: https://github.

namespace JWTS.Controllers
{
  [Route("api/[controller]")]
  [ApiController]
  public class AuthenticationController : ControllerBase
  {
    #region 构造函数
    private ILogger<AuthenticationController> _logger;
    private IJWTService _iJWTService;
    private readonly IConfiguration _iConfiguration;
    public AuthenticationController(ILogger<AuthenticationController> logger,
      IConfiguration configuration
      , IJWTService service)
    {
      _logger = logger;
      _iConfiguration = configuration;
      _iJWTService = service;
    }
    #endregion

/// <summary>
    /// 实际场景使用Post方法
    ///http://localhost:5000/api/Authentication/Login?name=william&password=123123

/// </summary>
    /// <param></param>
    /// <param></param>
    /// <returns></returns>
    [Route("Login")]
    [HttpGet]
    public IActionResult Login(string name, string password)
    {
      //这里应该是需要去连接数据库做数据校验,为了方便所有用户名和密码写死了
      if ("william".Equals(name) && "123123".Equals(password))//应该数据库
      {
        var role = "Administrator";//可以从数据库获取角色
        string token = this._iJWTService.GetToken(name, role);
        return new JsonResult(new
        {
          result = true,
          token
        });
      }

return Unauthorized("Not Register!!!");
    }
  }
}

2、资源中心API:使用从认证服务中心获取的Token,去访问资源,资源中心对用户信息以及Token进行鉴权操作,认证失败返回401

1、资源中心添加Nuget包(Microsoft.AspNetCore.Authentication.JwtBearer)

2、添加Authentication服务,添加JwtBearer,通过Configuration获取TokenParameter对象

(编辑:惠州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读