溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在ASP.NET Core中如何實(shí)現(xiàn)一個(gè)Token base的身份認(rèn)證

發(fā)布時(shí)間:2021-08-26 15:31:47 來(lái)源:億速云 閱讀:151 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)在ASP.NET Core中如何實(shí)現(xiàn)一個(gè)Token base的身份認(rèn)證,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)建項(xiàng)目

在VS中新建項(xiàng)目,項(xiàng)目類型選擇ASP.NET Core Web Application(.NET Core), 輸入項(xiàng)目名稱為CSTokenBaseAuth

Coding

創(chuàng)建一些輔助類

在項(xiàng)目根目錄下創(chuàng)建一個(gè)文件夾Auth,并添加RSAKeyHelper.cs以及TokenAuthOption.cs兩個(gè)文件

在RSAKeyHelper.cs中

using System.Security.Cryptography;

namespace CSTokenBaseAuth.Auth
{
  public class RSAKeyHelper
  {
    public static RSAParameters GenerateKey()
    {
      using (var key = new RSACryptoServiceProvider(2048))
      {
        return key.ExportParameters(true);
      }
    }
  }
}

在TokenAuthOption.cs中

using System;
using Microsoft.IdentityModel.Tokens;

namespace CSTokenBaseAuth.Auth
{
  public class TokenAuthOption
  {
    public static string Audience { get; } = "ExampleAudience";
    public static string Issuer { get; } = "ExampleIssuer";
    public static RsaSecurityKey Key { get; } = new RsaSecurityKey(RSAKeyHelper.GenerateKey());
    public static SigningCredentials SigningCredentials { get; } = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature);

    public static TimeSpan ExpiresSpan { get; } = TimeSpan.FromMinutes(20);
  }
}

Startup.cs

在ConfigureServices中添加如下代碼:

services.AddAuthorization(auth =>
{
  auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme?)
    .RequireAuthenticatedUser().Build());
});

完整的代碼應(yīng)該是這樣

public void ConfigureServices(IServiceCollection services)
{
  // Add framework services.
  services.AddApplicationInsightsTelemetry(Configuration);
  // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
  services.AddAuthorization(auth =>
  {
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
      .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme?)
      .RequireAuthenticatedUser().Build());
  });
  services.AddMvc();
}

在Configure方法中添加如下代碼

app.UseExceptionHandler(appBuilder => {
  appBuilder.Use(async (context, next) => {
    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
    //when authorization has failed, should retrun a json message to client
    if (error != null && error.Error is SecurityTokenExpiredException)
    {
      context.Response.StatusCode = 401;
      context.Response.ContentType = "application/json";
      await context.Response.WriteAsync(JsonConvert.SerializeObject(
        new { authenticated = false, tokenExpired = true }
      ));
    }
    //when orther error, retrun a error message json to client
    else if (error != null && error.Error != null)
    {
      context.Response.StatusCode = 500;
      context.Response.ContentType = "application/json";
      await context.Response.WriteAsync(JsonConvert.SerializeObject(
        new { success = false, error = error.Error.Message }
      ));
    }
    //when no error, do next.
    else await next();
  });
});

這段代碼主要是Handle Error用的,比如當(dāng)身份認(rèn)證失敗的時(shí)候會(huì)拋出異常,而這里就是處理這個(gè)異常的。

接下來(lái)在相同的方法中添加如下代碼,

app.UseExceptionHandler(appBuilder => {
  appBuilder.Use(async (context, next) => {
    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

    //when authorization has failed, should retrun a json message to client
    if (error != null && error.Error is SecurityTokenExpiredException)
    {
      context.Response.StatusCode = 401;
      context.Response.ContentType = "application/json";

      await context.Response.WriteAsync(JsonConvert.SerializeObject(
        new { authenticated = false, tokenExpired = true }
      ));
    }
    //when orther error, retrun a error message json to client
    else if (error != null && error.Error != null)
    {
      context.Response.StatusCode = 500;
      context.Response.ContentType = "application/json";
      await context.Response.WriteAsync(JsonConvert.SerializeObject(
        new { success = false, error = error.Error.Message }
      ));
    }
    //when no error, do next.
    else await next();
  });
});

應(yīng)用JwtBearerAuthentication

app.UseJwtBearerAuthentication(new JwtBearerOptions {
  TokenValidationParameters = new TokenValidationParameters {
    IssuerSigningKey = TokenAuthOption.Key,
    ValidAudience = TokenAuthOption.Audience,
    ValidIssuer = TokenAuthOption.Issuer,
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.FromMinutes(0)
  }
});

完整的代碼應(yīng)該是這樣

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using CSTokenBaseAuth.Auth;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace CSTokenBaseAuth
{
  public class Startup
  {
    public Startup(IHostingEnvironment env)
    {
      var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

      if (env.IsEnvironment("Development"))
      {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
      }

      builder.AddEnvironmentVariables();
      Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
      // Add framework services.
      services.AddApplicationInsightsTelemetry(Configuration);

      // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
      services.AddAuthorization(auth =>
      {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
          .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme?)
          .RequireAuthenticatedUser().Build());
      });

      services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();

      app.UseApplicationInsightsRequestTelemetry();

      app.UseApplicationInsightsExceptionTelemetry();

      #region Handle Exception
      app.UseExceptionHandler(appBuilder => {
        appBuilder.Use(async (context, next) => {
          var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

          //when authorization has failed, should retrun a json message to client
          if (error != null && error.Error is SecurityTokenExpiredException)
          {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";

            await context.Response.WriteAsync(JsonConvert.SerializeObject(
              new { authenticated = false, tokenExpired = true }
            ));
          }
          //when orther error, retrun a error message json to client
          else if (error != null && error.Error != null)
          {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(
              new { success = false, error = error.Error.Message }
            ));
          }
          //when no error, do next.
          else await next();
        });
      });
      #endregion

      #region UseJwtBearerAuthentication
      app.UseJwtBearerAuthentication(new JwtBearerOptions {
        TokenValidationParameters = new TokenValidationParameters {
          IssuerSigningKey = TokenAuthOption.Key,
          ValidAudience = TokenAuthOption.Audience,
          ValidIssuer = TokenAuthOption.Issuer,
          ValidateIssuerSigningKey = true,
          ValidateLifetime = true,
          ClockSkew = TimeSpan.FromMinutes(0)
        }
      });
      #endregion

      app.UseMvc(routes =>
      {
        routes.MapRoute(
          name: "default",
          template: "{controller=Login}/{action=Index}");
      });
    }
  }
}

在Controllers中新建一個(gè)Web API Controller Class,命名為TokenAuthController.cs。我們將在這里完成登錄授權(quán)

在同文件下添加兩個(gè)類,分別用來(lái)模擬用戶模型,以及用戶存儲(chǔ),代碼應(yīng)該是這樣

public class User
{
  public Guid ID { get; set; }
  public string Username { get; set; }
  public string Password { get; set; }
}

public static class UserStorage
{
  public static List<User> Users { get; set; } = new List<User> {
    new User {ID=Guid.NewGuid(),Username="user1",Password = "user1psd" },
    new User {ID=Guid.NewGuid(),Username="user2",Password = "user2psd" },
    new User {ID=Guid.NewGuid(),Username="user3",Password = "user3psd" }
  };
}

接下來(lái)在TokenAuthController.cs中添加如下方法

private string GenerateToken(User user, DateTime expires)
{
  var handler = new JwtSecurityTokenHandler();
  
  ClaimsIdentity identity = new ClaimsIdentity(
    new GenericIdentity(user.Username, "TokenAuth"),
    new[] {
      new Claim("ID", user.ID.ToString())
    }
  );

  var securityToken = handler.CreateToken(new SecurityTokenDescriptor
  {
    Issuer = TokenAuthOption.Issuer,
    Audience = TokenAuthOption.Audience,
    SigningCredentials = TokenAuthOption.SigningCredentials,
    Subject = identity,
    Expires = expires
  });
  return handler.WriteToken(securityToken);
}

該方法僅僅只是生成一個(gè)Auth Token,接下來(lái)我們來(lái)添加另外一個(gè)方法來(lái)調(diào)用它

在相同文件中添加如下代碼

[HttpPost]
public string GetAuthToken(User user)
{
  var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

  if (existUser != null)
  {
    var requestAt = DateTime.Now;
    var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
    var token = GenerateToken(existUser, expiresIn);

    return JsonConvert.SerializeObject(new {
      stateCode = 1,
      requertAt = requestAt,
      expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
      accessToken = token
    });
  }
  else
  {
    return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
  }
}

該文件完整的代碼應(yīng)該是這樣

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Principal;
using Microsoft.IdentityModel.Tokens;
using CSTokenBaseAuth.Auth;

namespace CSTokenBaseAuth.Controllers
{
  [Route("api/[controller]")]
  public class TokenAuthController : Controller
  {
    [HttpPost]
    public string GetAuthToken(User user)
    {
      var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

      if (existUser != null)
      {
        var requestAt = DateTime.Now;
        var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
        var token = GenerateToken(existUser, expiresIn);

        return JsonConvert.SerializeObject(new {
          stateCode = 1,
          requertAt = requestAt,
          expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
          accessToken = token
        });
      }
      else
      {
        return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
      }
    }

    private string GenerateToken(User user, DateTime expires)
    {
      var handler = new JwtSecurityTokenHandler();
      
      ClaimsIdentity identity = new ClaimsIdentity(
        new GenericIdentity(user.Username, "TokenAuth"),
        new[] {
          new Claim("ID", user.ID.ToString())
        }
      );

      var securityToken = handler.CreateToken(new SecurityTokenDescriptor
      {
        Issuer = TokenAuthOption.Issuer,
        Audience = TokenAuthOption.Audience,
        SigningCredentials = TokenAuthOption.SigningCredentials,
        Subject = identity,
        Expires = expires
      });
      return handler.WriteToken(securityToken);
    }
  }

  public class User
  {
    public Guid ID { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }
  }

  public static class UserStorage
  {
    public static List<User> Users { get; set; } = new List<User> {
      new User {ID=Guid.NewGuid(),Username="user1",Password = "user1psd" },
      new User {ID=Guid.NewGuid(),Username="user2",Password = "user2psd" },
      new User {ID=Guid.NewGuid(),Username="user3",Password = "user3psd" }
    };
  }
}

接下來(lái)我們來(lái)完成授權(quán)驗(yàn)證部分

在Controllers中新建一個(gè)Web API Controller Class,命名為ValuesController.cs

在其中添加如下代碼

public string Get()
{
  var claimsIdentity = User.Identity as ClaimsIdentity;

  var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value;

  return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}";
}

為方法添加裝飾屬性

[HttpGet]
[Authorize("Bearer")]

完整的文件代碼應(yīng)該是這樣
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace CSTokenBaseAuth.Controllers
{
  [Route("api/[controller]")]
  public class ValuesController : Controller
  {
    [HttpGet]
    [Authorize("Bearer")]
    public string Get()
    {
      var claimsIdentity = User.Identity as ClaimsIdentity;

      var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value;

      return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}";
    }
  }
}

最后讓我們來(lái)添加視圖

在Controllers中新建一個(gè)Web Controller Class,命名為L(zhǎng)oginController.cs

其中的代碼應(yīng)該是這樣

using Microsoft.AspNetCore.Mvc;

namespace CSTokenBaseAuth.Controllers
{
  [Route("[controller]/[action]")]
  public class LoginController : Controller
  {
    public IActionResult Index()
    {
      return View();
    }
  }
}

在項(xiàng)目Views目錄下新建一個(gè)名為L(zhǎng)ogin的目錄,并在其中新建一個(gè)Index.cshtml文件。

代碼應(yīng)該是這個(gè)樣子

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <button id="getToken">getToken</button>
  <button id="requestAPI">requestAPI</button>

  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
    $(function () {
      var accessToken = undefined;

      $("#getToken").click(function () {
        $.post(
          "/api/TokenAuth",
          { Username: "user1", Password: "user1psd" },
          function (data) {
            console.log(data);
            if (data.stateCode == 1)
            {
              accessToken = data.accessToken;

              $.ajaxSetup({
                headers: { "Authorization": "Bearer " + accessToken }
              });
            }
          },
          "json"
        );
      })

      $("#requestAPI").click(function () {
        $.get("/api/Values", {}, function (data) {
          alert(data);
        }, "text");
      })
    })
  </script>
</body>
</html>

關(guān)于“在ASP.NET Core中如何實(shí)現(xiàn)一個(gè)Token base的身份認(rèn)證”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI