首页 .NET/Web NetCore之Token通行证的生成

NetCore之Token通行证的生成

作者:胡同里的砖头 围观群众:376 更新于:2021-12-22

创建一个新项目,我这里创建的是netcore3.1版本
安装依赖项
IdentityModel(5.2.0)
IdentityServer4(4.1.2)
Microsoft.AspNet.WebApi.Core(5.2.7)
Microsoft.AspNetCore.Authentication.JwtBearer(3.1.22)
Microsoft.Extensions.PlatformAbstractions(1.1.0)
System.IdentityModel.Tokens.Jwt(6.15.0)

新增一个Token的模板

using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace api
{
public class JwtSetting
{
/// <summary>
/// 颁发者
/// </summary>
public string Issuer { get; set; }

/// <summary>
/// 接收者
/// </summary>
public string Audience { get; set; }

/// <summary>
/// 令牌密码
/// </summary>
public string SecurityKey { get; set; }

/// <summary>
/// 过期时间
/// </summary>
public string ExpireSeconds { get; set; }

public SigningCredentials Credentials
{
get
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
return new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
}
}
}
}
令牌生成类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using IdentityModel;

namespace api
{
public interface ITokenService
{
string GetToken(User user);
}

public class TokenService : ITokenService
{
private readonly JwtSetting _jwtSetting;

public TokenService(IOptions<JwtSetting> option)
{
_jwtSetting = option.Value;
}

public string GetToken(User user)
{
//创建用户身份标识,可按需添加更多信息
var claims = new Claim[]
{
//new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("id", user.id.ToString(), ClaimValueTypes.Integer32),
new Claim("name", user.name)
};

//创建令牌
var token = new JwtSecurityToken(
issuer: _jwtSetting.Issuer,
audience: _jwtSetting.Audience,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: _jwtSetting.Credentials,
claims: claims
);

string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

return jwtToken;
}
}
}
再来一个模拟的用户类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace api
{
public class User
{
public int id { get; set; }
public string name { get; set; }
public string login { get; set; }
}
}
在appsettings.json里面配置如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"JwtSetting": {
"SecurityKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx", // 密钥
"Issuer": "jwtIssuertest", // 颁发者
"Audience": "jwtAudiencetest" // 接收者
},
"AllowedHosts": "*"
Startup代码如下:
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;

namespace api
{
public class Startup
{

public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<JwtSetting>(Configuration.GetSection("JwtSetting"));
services.AddScoped<ITokenService, TokenService>();

var jwtSetting = new JwtSetting();
Configuration.Bind("JwtSetting", jwtSetting);

services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
//NameClaimType = JwtClaimTypes.JwtId,
//RoleClaimType = JwtClaimTypes.Role,

ValidateIssuer = true,
ValidIssuer = jwtSetting.Issuer,

ValidateAudience = true,
ValidAudience = jwtSetting.Audience,

ValidateIssuerSigningKey = true, //是否验证SecurityKey
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSetting.SecurityKey))

};
});

services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://localhost:9528/*")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});

services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<CorsMiddleware>();
//使用认证中间件 app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

////===================================
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true));
////===================================
}
}
}
写一个简单的接口
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace api.Controllers
{
/// <summary>
/// 用户接口
/// </summary>
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{

private readonly ILogger<UserController> _logger;
private readonly ITokenService _tokenService;

public UserController(ILogger<UserController> logger, ITokenService tokenService)
{
_logger = logger;
_tokenService = tokenService;
}

/// <summary>
/// 登录获取Token
/// </summary>
/// <param name="login"></param>
/// <param name="pwd"></param>
/// <returns></returns>
[HttpGet]
public async Task<object> Login(string login,string pwd)
{
User user = new User();
//var user = await userDal.GetUser(username, password);
if (login!="test")
{
var res = new
{
code = 40000,
status = false,
message = "用户名或密码不正确"
};

return JsonConvert.SerializeObject(res);
}

user.id = 1;
user.login = "test";
user.name = "测试员";
var jwtToken = _tokenService.GetToken(user);

var response = new
{
code = 20000,
token = jwtToken,
type = "Bearer"

};

return response;
}
}
}
运行结果如图:


  • 本文标题: NetCore之Token通行证的生成
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8