API配置

可以使用ASP.NET Core Web API模板。同样,我们建议您控制端口并使用与之前一样的方法来配置Kestrel和启动配置文件。端口配置为http://localhost:5001

在项目Api中添加一个IdentityController控制器代码如下:

[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}

稍后将使用此控制器来测试授权要求,并通过API返回的数据显示身份声明。

配置AccessTokenValidation

添加NuGet包IdentityServer4.AccessTokenValidation到项目中

更新Startup.cs代码如下:

namespace API
{
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.AddMvcCore()
.AddAuthorization()//添加身份验证服务
.AddJsonFormatters();
//AddAuthentication将身份验证服务添加到DI并配置"Bearer"为默认方案
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";//identifyServer服务地址
options.RequireHttpsMetadata = false;//是否使用https options.ApiName = "api1";//进行身份验证的API资源的名称
});
} // 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();
}
}
}

AddAuthentication将认证服务添加到DI并配置"Bearer"为默认方案。AddIdentityServerAuthenticationIdentityServer访问令牌验证处理程序添加到DI以供验证服务使用。 UseAuthentication将认证中间件添加到请求管道中,以便每次调用主机时自动执行认证。

如果您使用浏览器导航到控制器(http://localhost:5001/identity),则应该获得401状态码。这意味着您的API需要一个凭证。

就是这样,API现在由IdentityServer保护。

WEB配置

最后一步是编写一个客户端请求访问令牌,然后使用此令牌访问该API。

IdentityServer中的令牌端点实现了OAuth 2.0协议,您可以使用原始HTTP访问它。然而,我们有一个名为IdentityModel的客户端库,它将协议交互封装在易于使用的API中。

官方源码参考地址:点击这里将 NuGet包IdentityModel添加到您的应用程序。

IdentityModel包含一个用于发现端点的客户端库。这样你只需要知道IdentityServer的访问地址 - 实际的端点地址可以从元数据中读取

// 从元数据中发现端口
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}

接着你可以使用 TokenClient 来请求令牌。为了创建一个该类型的实例,你需要传入令牌端点地址、客户端id和密码。

然后你可以使用 RequestClientCredentialsAsync 方法来为你的目标 API 请求一个令牌:

// 请求令牌
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);

最后调用API。

为了发送访问令牌到 API,你一般要使用 HTTP 授权 header。这可以通过 SetBearerToken 扩展方法来实现:

// 调用api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}

依次启动项目QuickstartIdentityServer、API、WEB
最后查看输出结果

注意:默认情况下,访问令牌将包含关于作用域,生命周期(nbf和exp),客户端ID(client_id)和发行者名称(iss)的声明。

ASP.NET Core的身份认证框架IdentityServer4--(2)API跟WEB端配置的更多相关文章

  1. ASP.NET Core的身份认证框架IdentityServer4(6)- 开始

    安装和概述 启动一个新的IdentityServer项目有两种基本方法: 从头开始 从Visual Studio中的ASP.NET身份模板开始 如果从头开始,我们提供了一些文档.项目帮助和内存存储支持 ...

  2. ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问

    前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...

  3. ASP.NET Core的身份认证框架IdentityServer4(1)-特性一览

    IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.OpenID和OAuth 的区别请看 https://www.zhihu.com/ques ...

  4. ASP.NET Core的身份认证框架IdentityServer4(5)- 包和构建

    包和构建 IdentityServer有许多nuget包 IdentityServer4 nuget | github 包含IdentityServer核心对象模型,服务和中间件. 仅支持内存配置和用 ...

  5. ASP.NET Core的身份认证框架IdentityServer4(9)-使用OpenID Connect添加用户认证

    OpenID Connect OpenID Connect 1.0是OAuth 2.0协议之上的一个简单的身份层. 它允许客户端基于授权服务器执行的身份验证来验证最终用户的身份,以及以可互操作和类似R ...

  6. ASP.NET Core的身份认证框架IdentityServer4(3)-术语的解释

    IdentityServer4 术语 IdentityServer4的规范.文档和对象模型使用了一些你应该了解的术语. 身份认证服务器(IdentityServer) IdentityServer是一 ...

  7. ASP.NET Core的身份认证框架IdentityServer4(8)- 使用密码认证方式控制API访问

    前言 本文及IdentityServer这个系列使用的都是基于.net core 2.0的.上一篇博文在API项目中我使用了icrosoft.AspNetCore.Authentication.Jwt ...

  8. ASP.NET Core的身份认证框架IdentityServer4(4)- 支持的规范

    IdentityServer实现以下规范: OpenID Connect OpenID Connect Core 1.0 (spec) OpenID Connect Discovery 1.0 (sp ...

  9. ASP.NET Core的身份认证框架IdentityServer4--入门

    ASP.NET Core的身份认证框架IdentityServer4--入门 2018年08月11日 10:09:00 qq_42606051 阅读数 4002   https://blog.csdn ...

  10. ASP.NET Core的身份认证框架IdentityServer4--(3)令牌服务配置访问控制跟UI添加

    使用密码保护API OAuth 2.0 资源所有者密码授权允许一个客户端发送用户名和密码到IdentityServer并获得一个表示该用户的可以用于访问api的Token. 该规范建议仅对" ...

随机推荐

  1. Hadoop问题:The auxService:mapreduce_shuffle does not exist

    问题描述:The auxService:mapreduce_shuffle does not exist INFO mapreduce.Job: Task Id : attempt_146180833 ...

  2. linux如何安装java环境

    linux安装jdk7步骤: 1.首先使用命令查看linux系统版本号: lsb_release -a 11 2.下载对应的jdk版本,笔者使用的是jdk-7u79-linux-x64.tar.gz: ...

  3. 使用非java代码编程

    使用非JAVA代码     JAVA语言及其标准API(应用程序编程接口)应付应用程序的编写已绰绰有余.但在某些情况下,还是必须使用非JAVA编码.例如,我们有时要访问操作系统的专用特性,与特殊的硬件 ...

  4. 关于Mysql模糊查询的优化-全文检索和Like的使用

    表A:CREATE TABLE `tableA` (`id` int(11) NOT NULL auto_increment,`content` varchar(256) default NULL,P ...

  5. Linux常用命令(一)--系统命令

    命令字 命令字 [命令选项] [命令参数] 1. 命令中所有字符区分大小写 2. 命令选项分为短格式(-)及长格式(–) 3. 必须在命令行提示符下输入命令 4. 命令中的各个部分至少需要一个空格分隔 ...

  6. func_get_args  获取一个函数的所有参数

    func_get_args  获取一个函数的所有参数 {     $numargs = func_num_args(); //参数数量     echo "参数个数是: $numargs&l ...

  7. python字符串问题

    相关知识点: 字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unico ...

  8. MySQL主从复制-xtrabackup的使用与延时复制(附原理图)

    标签(linux): mysql 笔者Q:972581034 交流群:605799367.有任何疑问可与笔者或加群交流 xtrabackup是percona公司针对MySQL开发的一款开源的物理备份工 ...

  9. java.lang.String中[ "张飞"+1+1 ] 和 [ "张飞"+(1+1) ]

    废话不多说,上代码: package com.core; public class StringTest { public static void main(String[] args) { Stri ...

  10. exp/imp 多用户导入导出

    创建用户 创建三个用户test1,test2,test3及表table1,table2,table3 SQL> create user test1 identified by test1 def ...