一、配置管理
1,读取内存配置
using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{ Dictionary<string, string> dic = new Dictionary<string, string>() {
{ "name","hunter"},
{ "age",""}
}; var builder = new ConfigurationBuilder()
.AddInMemoryCollection(dic)//当age没有值的时候使用dic里面的值
.AddCommandLine(args); var configuration = builder.Build(); Console.WriteLine($"name:{configuration["name"]}");
Console.WriteLine($"age:{configuration["age"]}"); Console.ReadKey();
}
}
}
demo
2,读取json文件
using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("class.json"); var configuration = builder.Build(); Console.WriteLine($"no:{configuration["no"]}");
Console.WriteLine($"name:{configuration["name"]}");
Console.WriteLine("student:");
Console.WriteLine($"no:{configuration["student::no"]},name:{configuration["student::name"]}");
Console.WriteLine($"no:{configuration["student::no"]},name:{configuration["student::name"]}"); Console.ReadKey();
}
}
}
demo
{
"no": "",
"name": "asp.net core",
"student": [
{
"no": "",
"name": "张三"
},
{
"no": "",
"name": "张三"
}
]
}
class.json
3,读取appsettings.json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
} public IActionResult Index()
{
Class c = new Class();
_configuration.Bind(c); return View();
}
}
}
构造注入iconfiguration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebApplication1
{
public class Class
{
public string no { get; set; }
public string name { get; set; }
public IEnumerable<student> student { get; set; }
} public class student {
public string no { get; set; }
public string name { get; set; }
}
}
Class类
{
"no": "",
"name": "asp.net core",
"student": [
{
"no": "",
"name": "张三"
},
{
"no": "",
"name": "张三"
}
]
}
appsettings.json
二、管道
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http; namespace test2
{
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();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} //管道被截断 url:http://ip:port/test
app.Map("/test",testApp=>{
testApp.Run(async(context)=>{
await context.Response.WriteAsync("test");
});
}); //管道插入
app.Use(async (context,next)=>{
await context.Response.WriteAsync("");
await next.Invoke();
}); //管道插入
app.Use(next=>{
return (context)=>{
return context.Response.WriteAsync("");
};
}); app.UseStaticFiles(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Startup
1,模拟RequestDelegete
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace test3
{
class Program
{
public static List<Func<RequestDelegete,RequestDelegete>> _list=new List<Func<RequestDelegete, RequestDelegete>>();
static void Main(string[] args)
{
Use(next=>{
return (context)=>{
Console.WriteLine();
return Task.CompletedTask;
//return next.Invoke(context);
};
}); Use(next=>{
return (context)=>{
Console.WriteLine();
return next.Invoke(context);
};
}); RequestDelegete end=(context)=>{
Console.WriteLine("end");
return Task.CompletedTask;}; _list.Reverse();
foreach(var item in _list)
{
end=item.Invoke(end);
}
end.Invoke(new Context()); Console.ReadKey();
} public static void Use(Func<RequestDelegete,RequestDelegete> func)
{
_list.Add(func);
} }
}
Program
using System;
using System.Threading.Tasks; namespace test3
{
public delegate Task RequestDelegete(Context context);
}
RequestDelegete
namespace test3
{
public class Context
{ }
}
Context
三、认证与授权
1,Cookie-based认证
①注册Cookie认证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; namespace cookieBased
{
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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option=>{
option.LoginPath="/Login/Index";
}); 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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); //添加认证中间件
app.UseAuthentication(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Startup
②实现登录与注销
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using cookieBased.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims; namespace cookieBased.Controllers
{
public class LoginController:Controller
{
[HttpGet]
public IActionResult Index(string returnUrl)
{
ViewData["returnUrl"]=returnUrl;
return View();
} [HttpPost]
public IActionResult LoginIn(string returnUrl)
{
ClaimsIdentity identity=new ClaimsIdentity (new List<Claim>(){
new Claim(ClaimTypes.Name,"hunter"),
new Claim(ClaimTypes.Role,"admin")
},CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity)); var user= HttpContext.User.Identity.Name;
var b= HttpContext.User.Identity.IsAuthenticated; return Redirect(returnUrl);
} [HttpPost]
public IActionResult LoginOut()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
} }
}
LoginController
案例下载:https://pan.baidu.com/s/15etE9CNfzDLCHW6ZHc-euw
2,JWT认证
jwt验证网站: https://jwt.io/
namespace JwtAuthenticate.Models
{
public class JwtSettings
{
//token是谁颁发的
public string Issure{get;set;}
//可以给那些客户端使用
public string Audience{get;set;}
//需要加密的Secretkey
public string Secretkey{get;set;}
}
}
JwtAuthenticate.Models.JwtSettings
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"JwtSettings":{
"Audience":"http://localhost:5000",
"Issure":"http://localhost:5000",
"SecretKey":""
}
}
appsettings.json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using JwtAuthenticate.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text; namespace JwtAuthenticate
{
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)
{
//将配置文件jwtSettings注册进来
//public AuthorizeController(IOptions<JwtSettings> jwtSettings)会使用到
services.Configure<JwtSettings>(Configuration.GetSection("jwtSettings")); var jwtSettings=new JwtSettings();
Configuration.Bind("JwtSettings",jwtSettings); services.AddAuthentication(options=>{//配置Authentication
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options=>{//配置JwtBearer
options.TokenValidationParameters=new TokenValidationParameters{
ValidIssuer=jwtSettings.Issure,
ValidAudience=jwtSettings.Audience,
IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secretkey))
};
}); 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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseAuthentication();
app.UseMvc();
}
}
}
Startup
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JwtAuthenticate.Models;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt; namespace JwtAuthenticate.Controllers
{ [Route("api/[controller]")]
public class AuthorizeController:Controller
{
private JwtSettings _jwtSettings;
public AuthorizeController(IOptions<JwtSettings> jwtSettings)
{
_jwtSettings=jwtSettings.Value;
} [HttpGet]
public string A()
{
return "a";
} [HttpPost]
public IActionResult Token([FromBody]LoginViewModel model)
{
if(!ModelState.IsValid)return BadRequest();
if(!(model.UserName=="hunter"&&model.Password==""))return BadRequest(); var claims=new Claim[]{
new Claim(ClaimTypes.Name,"hunter"),
new Claim(ClaimTypes.Role,"admin")
}; var key=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secretkey));
var creds=new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
var token=new JwtSecurityToken(
_jwtSettings.Issure
,_jwtSettings.Audience
,claims,DateTime.Now,DateTime.Now.AddMinutes()
,creds);
return Ok(new {token=new JwtSecurityTokenHandler().WriteToken(token)});
} }
}
AuthorizeController
3,基于Claim的Jwt认证
①加上authorize标签
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization; namespace JwtAuthenticate.Controllers
{ [Route("api/[controller]")]
public class ValuesController : Controller
{ [Authorize(Policy="values.Get")] // GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} [Authorize(Policy="values.Get")]
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
} [Authorize(Policy="values.Post")]
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
} [Authorize(Policy="values.Put")]
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
} [Authorize(Policy="values.Delete")]
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
ValuesController
②设置Policy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using JwtAuthenticate.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text; namespace JwtAuthenticate
{
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)
{
//将配置文件jwtSettings注册进来
//public AuthorizeController(IOptions<JwtSettings> jwtSettings)会使用到
services.Configure<JwtSettings>(Configuration.GetSection("jwtSettings")); var jwtSettings=new JwtSettings();
Configuration.Bind("JwtSettings",jwtSettings); services.AddAuthentication(options=>{//配置Authentication
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options=>{//配置JwtBearer
options.TokenValidationParameters=new TokenValidationParameters{
ValidIssuer=jwtSettings.Issure,
ValidAudience=jwtSettings.Audience,
IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secretkey))
};
}); //设置policy
services.AddAuthorization(option=>{
option.AddPolicy("values.Get",policy=>{policy.RequireClaim("values.Get");});
option.AddPolicy("values.Post",policy=>{policy.RequireClaim("values.Post");});
option.AddPolicy("values.Delete",policy=>{policy.RequireClaim("values.Delete");});
option.AddPolicy("values.Put",policy=>{policy.RequireClaim("values.Put");});
}); 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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseAuthentication();
app.UseMvc();
}
}
}
Startup
③授权
只能访问values.Get和values.Put了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JwtAuthenticate.Models;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt; namespace JwtAuthenticate.Controllers
{ [Route("api/[controller]")]
public class AuthorizeController:Controller
{
private JwtSettings _jwtSettings;
public AuthorizeController(IOptions<JwtSettings> jwtSettings)
{
_jwtSettings=jwtSettings.Value;
} [HttpGet]
public string A()
{
return "a";
} [HttpPost]
public IActionResult Token([FromBody]LoginViewModel model)
{
if(!ModelState.IsValid)return BadRequest();
if(!(model.UserName=="hunter"&&model.Password==""))return BadRequest(); var claims=new Claim[]{
new Claim(ClaimTypes.Name,"hunter"),
new Claim("values.Get","true"),
new Claim("values.Put","true")
}; var key=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secretkey));
var creds=new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
var token=new JwtSecurityToken(
_jwtSettings.Issure
,_jwtSettings.Audience
,claims,DateTime.Now,DateTime.Now.AddMinutes()
,creds);
return Ok(new {token=new JwtSecurityTokenHandler().WriteToken(token)});
} }
}
AuthorizeController
案例下载:https://pan.baidu.com/s/1NKJNVMIHeVdPFcua_eH1sQ
四、MVCDemo
使用 dotnet new mvc -au individual -uld 创建mvc模板
1,项目启动创建种子数据
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using Microsoft.AspNetCore.Identity;
using mvcDemo2.Data; namespace mvcDemo2.Data
{
public class DbContextSeed
{
public void Seed(DemoDbContext context,IServiceProvider service)
{
if(!context.Users.Any())
{
var usermanager=service.GetRequiredService<UserManager<DemoUser>>();
var result= usermanager.CreateAsync(new DemoUser (){
UserName="admin",
NormalizedUserName="admin"
},"").Result;
if(!result.Succeeded)throw new Exception("创建管理员失败");
}
}
}
}
DbContextSeed
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace mvcDemo2.Data
{
public static class WebHostMigrationExtensions
{
public static IWebHost MigrationDbContext<TContext>(this IWebHost webhost,Action<TContext,IServiceProvider> sedder)
where TContext:DbContext
{
//使用依赖注入,并且在此using中有效
using(var scope=webhost.Services.CreateScope())
{
var service= scope.ServiceProvider;
var logger= service.GetRequiredService<ILogger<TContext>>();
var context=service.GetRequiredService<TContext>();
try
{
//当数据库不存在会创建数据库
context.Database.Migrate();
sedder(context,service);
}
catch (System.Exception ex)
{
logger.LogError(ex.Message);
}
}
return webhost;
}
}
}
WebHostMigrationExtensions
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using mvcDemo2.Data; namespace mvcDemo2
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args)
.MigrationDbContext<DemoDbContext>((context,service)=>{
new DbContextSeed().Seed(context,service);
})
.Run();
} public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
Program
案例下载:https://pan.baidu.com/s/1y1B3Vnudkke71eIuPQ937A
五、IdentityServer4
1,OAuth2.0密码登录模式(内存操作)
①IdentityServerCenter
nuget: IdentityServer4
using System.Collections.Generic;
using IdentityServer4.Models;
using IdentityServer4.Test;
namespace IdentityServerCenter
{
public class Config
{
//所有可以访问的对象
public static IEnumerable<ApiResource> GetApiResource(){
return new List<ApiResource>(){
new ApiResource("api","api resource")
};
} //客户端配置
public static IEnumerable<Client> GetClient(){
return new List<Client>(){
new Client(){
ClientId="",
AllowedGrantTypes={GrantType.ResourceOwnerPassword},//访问模式
RequireConsent=false,
ClientSecrets={
new Secret("secret".Sha256())
},
AllowedScopes={"api"},//可以访问的resource
//AllowOfflineAccess=true,//使用refresh_token
AccessTokenLifetime=
} };
}
public static List<TestUser> GetUsers(){
return new List<TestUser>(){
new TestUser(){
SubjectId="",
Username="hunter",
Password=""
}
};
} }
}
Config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using IdentityServer4; namespace IdentityServerCenter
{
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.AddIdentityServer()
.AddDeveloperSigningCredential()//设置临时签名凭证
.AddInMemoryApiResources(Config.GetApiResource())//添加api资源
.AddInMemoryClients(Config.GetClient())//添加客户端
.AddTestUsers(Config.GetUsers());//添加测试用户 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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer();
app.UseMvc();
}
}
}
Startup
②ApiResource
nuget: IdentityServer4.AccessTokenValidation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using IdentityServer4.AccessTokenValidation; namespace ApiResource
{
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.AddAuthentication("Bearer")//采用Bearer验证类型
.AddIdentityServerAuthentication(Options=>{
Options.ApiName="api";
Options.Authority="http://localhost:5000";
Options.RequireHttpsMetadata=false;//是否需要https
}); 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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//加上认证中间件
app.UseAuthentication();
app.UseMvc();
}
}
}
Startup
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; namespace ApiResource
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
} public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5001")
.Build();
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization; namespace ApiResource.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
} // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
Controllers
③ThreeClient
nuget: IdentityModel
using System;
using IdentityModel.Client;
using System.Net.Http; namespace ThreeClient
{
class Program
{
static void Main(string[] args)
{
//访问授权服务器
var diso= DiscoveryClient.GetAsync("http://localhost:5000").Result;
if(diso.IsError)
{
Console.WriteLine(diso.Error);
}
var tokenClient=new TokenClient(diso.TokenEndpoint,"","secret");
var res= tokenClient.RequestResourceOwnerPasswordAsync("hunter","").Result;
if(res.IsError)
{
Console.WriteLine(res.Error);
}
else
{
Console.WriteLine(res.Json);
} //访问资源服务器
var client=new HttpClient();
client.SetBearerToken(res.AccessToken);
var result= client.GetAsync("http://localhost:5001/api/values").Result;
if(result.IsSuccessStatusCode)
{
Console.WriteLine(result.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("失败");
} }
}
}
Program
案例下载:https://pan.baidu.com/s/1zoX3P5yuktW_HaaOGRGFOQ
2,刷新token
,
3,OAuth2.0密码模式(数据库操作)
4,OIDC(内存模式)
①介绍
OpenID Connect是OpenID的升级版,简称OIDC。OIDC使用OAuth2的授权服务器来为第三方客户端提供用户的身份认证,并把对应的身份认证信息传递给客户端 。
OAuth2.0主要用于授权。OIDC主要用来认证
5,OIDC(数据库模式)