program.cs
using CQIE.Books.DataAccesss.Imps;
using CQIE.Books.DataAccesss.Interfaces;
using CQIE.Books.Models;
using CQIE.Books.Public;
using CQIE.Books.Public.Consult;
using CQIE.Books.Public.JwtHelp;
using FreeRedis;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
// 添加服务到容器
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.RegisterService(configuration);
builder.Services.AddControllers();
builder.Services.AddScoped<_DbContext>();
builder.Services.AddScoped<IBooksService, BooksService>();
builder.Services.AddScoped<CQIE.Books.DataAccesss.Imps.IInventoryService, CQIE.Books.DataAccesss.Imps.IInventoryService>();
// ... 其他服务注册
// Jwt注册
builder.Services.AddSingleton(new JwtHelp(configuration));
// 跨域配置
var corsname = "any";
builder.Services.AddCors(options =>
{
options.AddPolicy(corsname, builder =>
{
builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
});
});
// 配置Redis
string redisConnectionString = builder.Configuration.GetSection("RedisCon").Value;
builder.Services.AddSingleton(r =>
{
var cli = new RedisClient(redisConnectionString);
// ... Redis客户端配置
return cli;
});
// 配置JWT认证
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = configuration["Jwt:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
RequireExpirationTime = true,
};
});
var app = builder.Build();
// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// 调用中间件:UseAuthentication(认证),必须在所有需要身份认证的中间件前调用
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.MapControllers();
app.Run();
appsetting
(AllowedHosts里面是consul)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DBConnectionStrings": {
"ManagerDB": {
"DBType": "MYSQL",
"server=localhost;user=root;database=Cqie.books3;port=;password=;"
}
},
"AllowedHosts": "*",
"ConsulConfig": {
"ConsulServer": "http://localhost:8500",
"DataCenter": "图书管理",
"Services": [
{
"APIAddress": "localhost",
"APIPort": 7020,
"APIName": "api/getbooks",
"APICheckAddress": "api/Books/GetBooks_1"
},
{
"APIAddress": "localhost",
"APIPort": 7020,
"APIName": "api/getonebook",
"APICheckAddress": "api/Books/GetBookByid"
},
{
"APIAddress": "localhost",
"APIPort": 7020,
"APIName": "api/ServiceThree",
"APICheckAddress": "api/Inventory/ServiceThree"
},
{
"APIAddress": "localhost",
"APIPort": 7020,
"APIName": "api/textAsync",
"APICheckAddress": "api/Inventory/textAsync"
}
]
},
"RedisCon": ",password=,defaultDatabase=1",
"Jwt": {
"SecretKey": "o9enoj6WoLVoPSEce-eofO4n_cyyrqzso15jdNfFQw8p5nNiPRmBM98NUpj_wwfQ4uFxohAUfvqsyBw2HzSCSg",
"Issuer": "WebAppIssuer",
"Audience": "WebAppAudience"
}
}
jwthelp.cs
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace CQIE.Books.Public.JwtHelp
{
public class JwtHelp
{
private readonly IConfiguration _configuration;
public JwtHelp(IConfiguration configuration)
{
_configuration = configuration;
}
public string CreateToken(string role)
{
// 1. 定义需要使用到的Claims
var claims = new[]
{
new Claim(ClaimTypes.Name, "u_admin"), //HttpContext.User.Identity.Name
new Claim(ClaimTypes.Role, role), //HttpContext.User.IsInRole("r_admin")
new Claim(JwtRegisteredClaimNames.Jti, "admin"),
new Claim("Username", "Admin"),
new Claim("Name", "www")
};
// 2. 从 appsettings.json 中读取SecretKey
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
// 3. 选择加密算法
var algorithm = SecurityAlgorithms.HmacSha256;
// 4. 生成Credentials
var signingCredentials = new SigningCredentials(secretKey, algorithm);
// 5. 根据以上,生成token
var jwtSecurityToken = new JwtSecurityToken(
_configuration["Jwt:Issuer"], //Issuer
_configuration["Jwt:Audience"], //Audience
claims, //Claims,
DateTime.Now, //notBefore
DateTime.Now.AddSeconds(300000), //expires
signingCredentials //Credentials
);
// 6. 将token变为string
var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
return token;
}
}
}
using CQIE.Books.Public.JwtHelp;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CQIE.Books.WebAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class JwttextController : Controller
{
private readonly JwtHelp _jwtHelper;
public JwttextController(JwtHelp jwtHelper)
{
_jwtHelper = jwtHelper;
}
[HttpGet]
public ActionResult<string> GetToken()
{
return _jwtHelper.CreateToken("admin");
}
[Authorize]
[HttpGet]
public ActionResult<string> GetTest()
{
return "Test Authorize";
}
}
}
以上是代码中使用
前端使用如下
try {
const response = await getUser(form.userName, form.passWord);
//const response = await getUser("1", "1");
console.log(response)
if (response.data.outcome) {
// Assuming 'form.userName' is the unique identifier for the user
// store.EditUserId(form.userName);
localStorage.setItem('userId', JSON.stringify(response.data.userId));
localStorage.setItem('userName', JSON.stringify(response.data.userName));
localStorage.setItem('token', response.data.token);
console.log(JSON.stringify(response.data.userId)+response.data.userName+response.data.token);
router.push({ path: '/First' });
return true;
} else {
alert("密码或者账户错误")
dialogVisible.value = true;
return false;
}
} catch (error) {
console.error('登录失败', error);
alert("密码或者账户错误")
return false;
}
fetchData() {
const jwt=localStorage.getItem('token');
const headers = {
Authorization: `Bearer ${jwt}`
};
axios.get('https://localhost:7252/webapi-1/Borrow/AllBorrow', { headers })
.then(response => {
this.listtableData = response.data;
this.isDataLoaded = true;
})
.catch(error => {
console.error('There was an error!', error);
});
},
ocelet中通过OcelotConfig设置对应签发信息的密钥
{
"Routes": [
{
"DownstreamPathTemplate": "/api/service1/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/service1/{everything}",
"UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
},
{
"DownstreamPathTemplate": "/api/{url}",
"UpstreamPathTemplate": "/webapi-1/{url}",
"UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ],
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7020
}
]
}
],
"GlobalConfiguration": {
"AuthenticationProviders": [
{
"Scheme": "o9enoj6WoLVoPSEce-eofO4n_cyyrqzso15jdNfFQw8p5nNiPRmBM98NUpj_wwfQ4uFxohAUfvqsyBw2HzSCSg",
"AuthenticationHandler": "JwtAuthenticationHandler"
}
],
"AuthenticationOptions": {
"AuthenticationProviderKeys": [ "o9enoj6WoLVoPSEce-eofO4n_cyyrqzso15jdNfFQw8p5nNiPRmBM98NUpj_wwfQ4uFxohAUfvqsyBw2HzSCSg" ],
"AllowedScopes": []
}
}
}
program内设置号签发人等,以及跨域
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// 跨域配置
var corsname = "any";
builder.Services.AddCors(options =>
{
options.AddPolicy(corsname, builder =>
{
builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
});
});
// 添加Controllers服务
builder.Services.AddControllers();
// 添加Swagger服务
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// 加载Ocelot配置文件
builder.Configuration.AddJsonFile("OcelotConfig.json");
// 添加JWT认证服务
var authenticationProviderKey = "o9enoj6WoLVoPSEce-eofO4n_cyyrqzso15jdNfFQw8p5nNiPRmBM98NUpj_wwfQ4uFxohAUfvqsyBw2HzSCSg";
builder.Services.AddAuthentication()
.AddJwtBearer(authenticationProviderKey, options =>
{
options.Authority = "WebAppIssuer";
options.Audience = "WebAppAudience";
// 其他JWT认证相关的配置
options.RequireHttpsMetadata = false;
});
// 添加Ocelot服务
builder.Services.AddOcelot(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// 使用跨域中间件
app.UseCors(corsname);
// 使用Ocelot中间件
app.UseOcelot();
// 使用认证中间件
app.UseAuthorization();
// 使用HTTPS重定向中间件
app.UseHttpsRedirection();
// 添加Controllers中间件
app.MapControllers();
app.Run();