.Net Core Api 授权认证
2021-02-16 20:19
标签:odi auth metrics date 返回 text res style mod 一、所使用到的NuGet: 1. System.IdentityModel.Tokens.Jwt 2. Microsoft.AspNetCore.Authentication.JwtBearer 二、在Startup.cs 中配置添加如下服务 三、签发token 添加测试控制器 四、访问结果 .Net Core Api 授权认证 标签:odi auth metrics date 返回 text res style mod 原文地址:https://www.cnblogs.com/haosit/p/8399048.htmlusing Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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.AddMvc();
//手动高亮
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = "haos.test.com",
//山下这两项和签发token时的issuer,Audience一致
ValidIssuer = "haos.test.issuer.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"))//拿到token加密密钥.必须是16个字符
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//手动高亮
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
}
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Linq;
namespace WebApplication1.Controllers
{
[Authorize]
public class TestController:Controller
{
public JsonResult Test()
{
//获取当前用户信息
var claims = User.Claims;
var userName = User.Identity.Name;
var userId = claims.FirstOrDefault(t => t.Type == "userId");
var phone = claims.FirstOrDefault(t => t.Type == ClaimTypes.MobilePhone);
return Json("ok");
}
///
//返回的token;注:键为authorization,其中必须有Bearer 字样
{"authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL21vYmlsZXBob25lIjoiMTU3KioqKjczNTAiLCJleHAiOjE1MTc0NjgzNDcsImlzcyI6Imhhb3MudGVzdC5pc3N1ZXIuY29tIiwiYXVkIjoiaGFvcy50ZXN0LmNvbSJ9.Xtrbbz6WF4VreoB-S2nmRL5lx1Vg27WcQYTsek5VPIc"}
文章标题:.Net Core Api 授权认证
文章链接:http://soscw.com/index.php/essay/56257.html