ASP.NET Core 는 JWT 인증 권한 을 부여 하 는 방법 을 사용 합 니 다.

11482 단어 ASP.NETCoreJWT인증
demo 주소:https://github.com/william0705/JWTS
명사 해석
인증:사용자 의 합 법 여 부 를 식별 합 니 다.
권한 부여:사용자 권한 부여(어떤 자원 에 접근 할 수 있 는 지)
감 권:감정 권한 이 합 법 적 인지 여부
Jwt 우세 와 열세
우세 하 다.
1.무상 태
token 은 인증 모든 정 보 를 저장 합 니 다.서버 는 사용자 인증 정 보 를 저장 하지 않 아 도 됩 니 다.서버 의 압력 을 줄 이 고 서버 가 수평 으로 확장 되 기 쉽 습 니 다.상태 가 없 으 면 최대 단점 을 초래 하여 로그아웃 하기 어렵 습 니 다.
2.크로스 도 메 인 접근 지원
Cookie 는 도 메 인 접근 을 허용 하지 않 습 니 다.token 지원
3.언어 간
표준 화 된 JSON Web Token(JWT)을 기반 으로 특정한 언어 에 의존 하지 않 습 니 다.예 를 들 어 생 성 된 Token 은 다양한 언어 에 사용 할 수 있 습 니 다(Net,Java,PHP...)
열세
1.Token 의 유효성 문제
백 스테이지 에서 발 표 된 Token 을 로그아웃 하기 어렵 습 니 다.보통 제3자 저장(데이터베이스/캐 시)을 통 해 로그아웃 을 해 야 합 니 다.그러면 JWT 의 가장 큰 장점 을 잃 게 됩 니 다.
2.대역 폭 차지
Token 길이(저장 내용 에 따라 다 름)비 sessionid 가 크 고 매번 요청 할 때마다 대역 폭 을 많이 소모 합 니 다.token 은 필요 한 정보 만 저장 하고 token 이 너무 길 지 않도록 합 니 다.
3.재계약 이 필요 하 다
cookies C session 은 보통 프레임 워 크 가 재계약 기능 을 실 현 했 고 매번 에 방문 할 때마다 기한 이 지난 시간 을 갱신 합 니 다.JWT 는 스스로 실현 해 야 합 니 다.OAuth 2 리 셋 Token 체 제 를 참고 하여 리 셋 Token 을 실현 합 니 다.
4、더 많은 CPU 소모
매번 요청 할 때마다 내용 복호화 와 서명 검증 두 단계 작업 이 필요 합 니 다.전형 적 으로 시간 으로 공간 을 바 꿉 니 다.
자신의 사용 장면 에 따라 어떤 인증 방안 을 사용 할 지 결정 할 수 있 을 뿐 통용 되 고 완벽 한 방안 은 없다.
.NET Core 통합 JWT 인증 권한 부여 서비스
1.인증 서비스 API:사용자 인증 및 Token 발표
1.nuget 패키지 도입,System.IdentityModel.Tokens.Jwt
2.Token 을 생 성 하 는 서 비 스 를 만 들 고 인터페이스 와 프로 그래 밍 을 실현 하 며 서비스 가 용기 ServicesCollection(DI 와 IOC 개념 관련)에 편리 하 게 주입 하 는 것 을 권장 합 니 다.
3.인터페이스 만 들 기

namespace JWTS.Services
{
  public interface IJWTService
  {
    /// <summary>
    ///                 Token,          
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="role"></param>
    /// <returns></returns>
    string GetToken(string userName,string role);
  }
}
4.apptsettings.config 에 token 생 성 에 필요 한 정 보 를 추가 하고 대상 으로 매 핑 합 니 다.

"TokenParameter": {
  "Issuer": "William", //  JWT     (   )
  "Audience": "William", //  JWT     
  "SecurityKey": "askalsnlkndhasnaslkasmadka"
 }

   public class TokenParameter
    {
        public string Issuer { get; set; }
        public string Audience { get; set; }
        public string SecurityKey { get; set; }
    }

5.인터페이스 구현,Configuration 주입,TokenParameter 대상 가 져 오기

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

namespace JWTS.Services
{
  public class JWTService : IJWTService
  {
    private readonly TokenParameter _tokenParameter;
      public JWTService(IConfiguration configuration)
          {
              _tokenParameter = configuration.GetSection("TokenParameter").Get<TokenParameter>();
          }
     /// <summary>
    /// JWT      (Header、Payload、Signature)
    /// {Header}.{Payload}.{Signature}
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="role"></param>
    /// <returns></returns>
    public string GetToken(string userName,string role)
    {
      Claim[] claims = new[]
      {
        new Claim(ClaimTypes.Name, userName),
        new Claim("NickName","Richard"),
        new Claim("Role",role)//      
      };
      SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.SecurityKey));
      SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
      /**
       * Claims (Payload)
        Claims            token        。 JWT          ,        :
        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: _tokenParameter.Issuer,
        audience: _tokenParameter.Audience,
        claims: claims,
        expires: DateTime.Now.AddMinutes(10),//10     
        signingCredentials: creds);
      string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
      return returnToken;
    }
  }
}

6.jwt 에서 정 의 된 Claims
JWT 표준 에 정 해진 claim 은 다음 과 같다.
  • iss(Issuser):이 JWT 의 발급 주 체 를 대표 합 니 다
  • sub(Subject):이 JWT 의 주체,즉 그의 모든 사람 을 대표 합 니 다
  • aud(Audience):이 JWT 의 수신 대상 을 대표 합 니 다
  • exp(Expiration time):하나의 시간 스탬프 로 이 JWT 의 만 료 시간 을 대표 합 니 다
  • nbf(Not Before):시간 스탬프 입 니 다.이 JWT 가 효력 이 발생 하 는 시작 시간 을 대표 합 니 다.이 시간 전에 JWT 를 검증 하 는 것 이 실패 할 것 임 을 의미 합 니 다
  • iat(Issued at):하나의 시간 스탬프 로 이 JWT 의 서명 시간 을 대표 합 니 다
  • jti(JWT ID):JWT 의 유일한 표지 이다
  • 7.인증 프로젝트 프로젝트 의 Startup.cs 파일 에서 JWT 를 주입 하 는 서비스 클래스 에 의존 합 니 다.
    
    public void ConfigureServices(IServiceCollection services) { services.AddScoped <IJWTService, JWTService> (); services.AddControllers(); }
    
    
    8.AuthenticationController 를 추가 하여 Token 을 생 성하 고 나중에 RefreshToken 을 추가 할 수 있 습 니 다.
    
    using JWTS.Services;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    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 name="name"></param>
        /// <param name="password"></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));
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
          services.AddControllers();
          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//      
            .AddJwtBearer(options =>
            {
              options.TokenValidationParameters=new TokenValidationParameters()
              {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = _tokenParameter.Issuer,
                ValidAudience = _tokenParameter.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.SecurityKey))
              };
            });
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          if (env.IsDevelopment())
          {
            app.UseDeveloperExceptionPage();
          }
    
          app.UseRouting();
          app.UseAuthentication();
          app.UseAuthorization();
    
          app.UseEndpoints(endpoints =>
          {
            endpoints.MapControllers();
          });
        }
      }
    }
    
    
    3.자원 컨트롤 러 에[Authorize]속성 을 추가 하여 인증 권한 을 사용 하여 API 자원 에 접근 합 니 다.
    
       [ApiController]
      [Route("[controller]")]
      [Authorize]
      public class WeatherForecastController : ControllerBase
      {
        private static readonly string[] Summaries = new[]
        {
          "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
    
        private readonly ILogger<WeatherForecastController> _logger;
    
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
          _logger = logger;
        }
    
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
          var rng = new Random();
          return Enumerable.Range(1, 5).Select(index => new WeatherForecast
          {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
          })
          .ToArray();
        }
      }
    
    ASP.NET Core 가 JWT 인증 권한 을 사용 하 는 방법 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 ASP.NET Core JWT 인증 권한 수여 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 부탁드립니다!

    좋은 웹페이지 즐겨찾기