加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-11-23 22:07:50 所属栏目:百科 来源:网络整理
导读:副标题#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对象

using System;
using System.Text;
using API.Core.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;

namespace API.Core
{
  public class Startup
  {
    private TokenParameter _tokenParameter;
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
      _tokenParameter = configuration.GetSection("TokenParameter").Get<TokenParameter>()??throw new ArgumentNullException(nameof(_tokenParameter));
    }

(编辑:PHP编程网 - 黄冈站长网)

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

热点阅读