feat: WebApi 接口开发

main
wanggaofeng 1 year ago
parent 02bc3ab3de
commit bcff6c45d8

@ -19,5 +19,7 @@
/// 密码
/// </summary>
public string? Password { get; set; }
public string Role { get; set; } = "Dev";
}
}

@ -1,13 +1,29 @@
using Microsoft.AspNetCore.Authorization;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using HttpClientStudy.Model;
using HttpClientStudy.WebApp.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
namespace HttpClientStudy.WebApp.Controllers
{
/// <summary>
/// 账号控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class AccountController : ControllerBase
{
/// <summary>
/// 构造
/// </summary>
public AccountController() { }
/// <summary>
@ -30,9 +46,80 @@ namespace HttpClientStudy.WebApp.Controllers
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
public IActionResult GetToken()
public IActionResult GetToken(string userName, string password)
{
var account = new Account() { Id = 1, Name = userName, Password = password, Role = "Admin" };
var principal = CreateClaimsPrincipal(account);
var token = CreateJwtToken(principal.Claims.ToList());
var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token };
var result = BaseResultUtil.Success(data);
return new JsonResult(result);
}
/// <summary>
/// 获取Token
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpPost]
public IActionResult GetToken(LoginAccount vm)
{
return new JsonResult(new { Code = 1, Message = "", Token = "a.b.c" });
var account = new Account() { Id = 1, Name = vm.Account, Password = vm.Password, Role = "Admin" };
var principal = CreateClaimsPrincipal(account);
var token = CreateJwtToken(principal.Claims.ToList());
var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token };
var result = BaseResultUtil.Success(data);
return new JsonResult(result);
}
/// <summary>
/// 生成ClaimsPrincipal
/// </summary>
private ClaimsPrincipal CreateClaimsPrincipal(Account account)
{
List<Claim> claims = new List<Claim>
{
new Claim("ID", account.Id.ToString()),
new Claim("Name",account.Name??""),
new Claim("Password", account.Password??"123123"),
new Claim("Role",account.Role),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
return principal;
}
/// <summary>
/// 生成JwtToken
/// </summary>
private string CreateJwtToken(List<Claim> claims)
{
//生成Jwt
//jwtTokenOptions 是通过配置获取上面配置的参数信息
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0123456789abcdefghigklmnopqrstdf41sadfweqtdfghsdfgsdfweqr"));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//令牌
var expires = DateTime.Now.AddDays(1);
var token = new JwtSecurityToken
(
issuer: "WWW.WANGGAOFENG.CN",
audience: "WWW.WANGGAOFENG.CN",
claims: claims,
notBefore: DateTime.Now,
expires: expires,
signingCredentials: credentials
);
string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
}
}
}

@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HttpClientStudy.WebApp.Controllers
{
/// <summary>
/// 简单接口 控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class SimpleController : ControllerBase
{
private ILogger<SimpleController> _logger;
/// <summary>
/// 构造
/// </summary>
public SimpleController(ILogger<SimpleController> logger)
{
_logger = logger;
}
/// <summary>
/// 获取账号
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult GetAccount()
{
var reslut = BaseResultUtil.Success("操作成功");
return Ok(reslut);
}
}
}

@ -1,15 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
</ItemGroup>
<ItemGroup>

@ -6,7 +6,7 @@ namespace HttpClientStudy.WebApp.Models
/// <summary>
/// 获取Token 请求类
/// </summary>
public class UserForToken
public class LoginAccount
{
/// <summary>
/// 账号

@ -1,33 +1,179 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace HttpClientStudy.WebApp
{
/// <summary>
/// HttpClient学习WebAPI项目
/// </summary>
public class Program
{
/// <summary>
/// Main
/// </summary>
/// <param name="args">启动参数</param>
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
#region 向容器注册服务
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
//Session中间件依赖项
builder.Services.AddDistributedMemoryCache();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
//配置Session
builder.Services.AddSession(option =>
{
app.UseSwagger();
app.UseSwaggerUI();
option.Cookie.Name = "HttpClientStudy";
option.IOTimeout = TimeSpan.FromHours(1);
option.IdleTimeout = TimeSpan.FromHours(1);
});
//配置Form表单提交选项
builder.Services.Configure<FormOptions>(options =>
{
//options.BufferBody = true;
options.MultipartBodyLengthLimit = long.MaxValue;
options.MultipartBoundaryLengthLimit = int.MaxValue;
options.MultipartHeadersCountLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
//配置Swagger
builder.Services.AddSwaggerGen(setup =>
{
#region 定义Swagger文档
//name参数即为SwaggerUI中SwaggerEndpoint方法参数中的{documentName}
//两者必须保持一致,否则异常
setup.SwaggerDoc(name: "v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "HttpClient学习", Version = "第1版" });
#endregion
#region 包含xml注释
var xmlCommentFiles = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "HttpClientStudy.*.xml", System.IO.SearchOption.TopDirectoryOnly);
foreach (var xmlFile in xmlCommentFiles)
{
//includeControllerXmlComments参数是否启用控制器上的xml注释
setup.IncludeXmlComments(filePath: xmlFile, includeControllerXmlComments: true);
setup.UseInlineDefinitionsForEnums();
}
#endregion
app.UseAuthorization();
#region 放置接口Auth授权按钮
setup.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "请输入带有Bearer的TokenBearer {Token}",
//jwt默认的参数名称
Name = "Authorization",
//jwt默认存放 Authorization 信息的位置:此处为请求头中
In = ParameterLocation.Header,
//验证类型此处使用Api Key
Type = SecuritySchemeType.ApiKey
});
#endregion
#region 指定方案应用范围
setup.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
#endregion
//启用数据注解
setup.EnableAnnotations();
});
//配置Cors跨域
builder.Services.AddCors(option =>
{
option.AddPolicy("AllowAll", builder =>
{
builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
});
});
//认证
builder.Services //认证基础架构
.AddAuthentication(authOption =>
{
authOption.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOption.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOption.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOption.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOption.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
//Cookie认证
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
{
option.Cookie.Name = ".eds.editor.cookie.authentication.oa2";//设置存储用户登录信息用户Token信息的Cookie名称
option.Cookie.HttpOnly = true;//设置存储用户登录信息用户Token信息的Cookie无法通过客户端浏览器脚本(如JavaScript等)访问到
option.ExpireTimeSpan = TimeSpan.FromDays(3);// 过期时间
option.SlidingExpiration = true;// 是否在过期时间过半的时候,自动延期
option.LoginPath = "/Account/Login";
option.LogoutPath = "/Account/LoginOut";
//option.AccessDeniedPath = "/Account/Login";
})
//认证
.AddJwtBearer(option =>
{
option.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "WWW.WANGGAOFENG.CN",
ValidAudience = "WWW.WANGGAOFENG.CN",
ValidateIssuer = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0123456789abcdefghigklmnopqrstdf41sadfweqtdfghsdfgsdfweqr")),
//缓冲过期时间总的有效时间等于这个时间加上jwt的过期时间
ClockSkew = TimeSpan.FromSeconds(0)
};
});
//授权
builder.Services.AddAuthorization();
#endregion
var app = builder.Build();
#region 配置Http管道
app.UseSwagger();
app.UseSwaggerUI(setup =>
{
setup.EnableDeepLinking();
setup.DisplayRequestDuration();
setup.ShowCommonExtensions();
setup.ShowExtensions();
setup.EnableFilter();
});
app.UseCors("AllowAll");
app.UseAuthorization();
app.MapControllers();
app.UseAuthorization();
#endregion
app.Run();
}
}

Loading…
Cancel
Save