IdentityServer4(一)使用客户端凭证方式
这个篇文章主要是记录自己参考官方文档搭建身份认证的过程
使用的.NET Core2.2
参考地址:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html
1.第一步,创建一个webapi的工程,要使用IDS4(IdentityServer4)做身份认证首先得在程序管理控制台导入IDS4的NuGet包:Install-Package IdentityServer4
2.因为客户端凭证的方式会在api根目录下生成一个tempkey.rsa文件,所以需要在在Starut.cs构造函数中注入IHostingEnvironment
public IHostingEnvironment Environment { get; }
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
Configuration = configuration;
Environment = environment;
}
3.导入IDS4的包之后我们需要在ConfigureServices中添加如下内容:
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
//.AddTestUsers(Config.GetUsers()); services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
#region 客户端凭证的方式需要添加此处代码生成证书
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
else
{
throw new Exception("need to configure key material");
}
#endregion services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
//开发环境禁用了https,默认为开开启
options.RequireHttpsMetadata = false; options.Audience = "api1";
});
4.在Configure中添加identityServer中间件:
//在UseMvc之前即可
app.UseIdentityServer();
然后我们在VaulesController中修改下代码,在后面客户端的时候用来测试
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
客户端需要导入IdentityModel Nuget包
下面代码中GetDiscoveryDocumentAsync()方法主要是从API服务的http://localhost:5000/.well-known/openid-configuration获取访问token的接口,即TokenEndpoint,debug可看到TokenEndpoint=http://localhost:5000/connect/token,经过验证直接将Addres赋值为http://localhost:5000/connect/token也是可以正常获取token的,查看IdentityModel源码也是在url中追加了/.well-known/openid-configuration
var _client = new HttpClient(); var disco = _client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
}
var tokenResponse = _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{ Address = disco.TokenEndpoint,
//Address="http://localhost:5000/connect/token",//直接使用获取token的地址
ClientId = "client",
ClientSecret = "secret",
Scope = "api1"
}).Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
Console.ReadKey();
return;
}
Console.WriteLine("============================客户端获取token================================================");
Console.WriteLine(tokenResponse.Json); _client.SetBearerToken(tokenResponse.AccessToken);
var response = _client.GetAsync("http://localhost:5000/api/Values").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(JArray.Parse(content));
}
以下是运行之后的结果
最新文章
- JQuery------分页插件下载地址
- Linux 信号(三)—— sigaction 函数
- Xcode5中如何切换Storyboards为xib
- Mysql学习笔记(四)聊聊数据库索引
- MySQL数据库百万级高并发网站实战
- exception is org.hibernate.exception.DataException: Could not execute JDBC batch update 	at
- BZOJ_1620_[Usaco2008_Nov]_Time_Management_时间管理_(二分+贪心)
- Segment对象
- 消息函数一般是私有的,因为不需要程序员显示的调用,但子类如果需要改写这个方法,则改成保护方法Protected
- win7下 mysql安装(mysql-5.7.18-winx64.zip)
- ArcGIS API for JavaScript 4.2学习笔记[23] 没有地图如何进行查询?【FindTask类的使用】
- Kubernetes 笔记 08 Deployment 副本管理 重新招一个员工来填坑
- 基本 SQL 之数据库及表管理
- MySQL与MongoDB
- windows phone 基础
- 犯罪心理第八季/全集Criminal Minds迅雷下载
- SQL Server表描述 及 字段描述的增、删、改、查询
- SharePoint自动化系列——通过PowerShell在SharePoint中批量做数据
- django 视图 使用orm values_list()方法获取 指定的 多个字段的数据
- Sencha Architect打开闪退问题修复
热门文章
- 洛谷 P1047 校门外的树
- Centos解除端口占用
- [配置] win下maven配置
- Spring Security框架下Restful Token的验证方案
- webstorm 2018 LICENSE SERVER 最新激活网址
- MySQL_视图
- 小程序wx.request的封装
- 解决: Homestead 环境下, yarn install --no-bin-links, NPM run dev, 命令报错
- centos7图形界面安装
- JSP+javaBean:简易投票网页练习