前言

客户端授权模,客户端直接向Identity Server申请token并访问资源。客户端授权模式比较适用于服务之间的通信。

搭建Identity服务

新建名为 IdentityServer 的WebApi空项目,设置端口为5000,作为我们的授权认证服务。

新建名为 Api 的WebApi空项目,设置端口为5001,作为我们的Api资源。

通过NuGet安装 IdentityServer4 或者通过程序包管理执行 Install-Package IdentityServer4 安装依赖包。

新一个 Config 文件来定义Identity资源

using System.Collections.Generic;
using IdentityServer4;
using IdentityServer4.Models; namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> GetIdentityResourceResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误
};
}
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
//api资源({资源名称}{描述})
return new List<ApiResource>
{
new ApiResource("Api", "Api"),
};
} // clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
//客户端id,必须唯一
ClientId = "client_a",
//授权方式,这里采用的是客户端认证模式,只要ClientId,以及ClientSecrets正确即可访问对应的AllowedScopes里面的api资源
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes =
{
"Api",
}
}
};
}
}
}

Startup 中配置IdentityServer

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; namespace IdentityServer
{
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)
{
//注入DI
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())//Api资源信息
.AddInMemoryClients(Config.GetClients());//客户端信息
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//放入HTTP管道中
app.UseIdentityServer();
}
}
}

运行当前项目,并访问 http://localhost:5000/.well-known/openid-configuration 就会看到当前IdentityServer的一些信,首次启动会创建一个名为tempkey.rsa 的文件,里面保存的是你的签名密钥。

定义Api资源

通过NuGet安装 IdentityServer4.AccessTokenValidation 或者通过程序包管理执行 IInstall-Package IdentityServer4.AccessTokenValidation 安装依赖包。

Api 项目中新增一个ValuesController并添加一个 Print 接口 Authorize表示该接口被身份认证所保护

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace Api.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet("Print")]
[Authorize]
public ActionResult Print()
{
return new JsonResult("hello word");
}
}
}

Startup 中把身份认证服务注入DI,并放入HTTP管道。

uusing Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
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.AddControllers();
//将身份认证注入到DI
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "Api";
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); //身份认证添加到HTTP管道
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

测试效果

我们同时运行两个项目。这时候我们直接访问Api资源。会直接抛出401(用户没有权限访问)

我们用配置的client向IdentityServer申请token来访问Api资源

client_id - 我们配置的客户端id

client_secret - 签名密钥。

grant_type - 授权模式

access_token - 访问令牌

expires_in - 过去时间(秒)

token_type - 令牌类型

scope - 可以访问资源名称

使用资源访问Api资源,在Hraders中加入 authorization 传入刚申请的token(Bearer后面有一个空格)

IdentityServer(二)客户端授权模式的更多相关文章

  1. IdentityServer4 (1) 客户端授权模式(Client Credentials)

    写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...

  2. IdentityServer4(客户端授权模式)

    1.新建三个项目 IdentityServer:端口5000 IdentityAPI:端口5001 IdentityClient: 2.在IdentityServer项目中添加IdentityServ ...

  3. IdentityServer4[3]:使用客户端认证控制API访问(客户端授权模式)

    使用客户端认证控制API访问(客户端授权模式) 场景描述 使用IdentityServer保护API的最基本场景. 我们定义一个API和要访问API的客户端.客户端从IdentityServer请求A ...

  4. (十)React Ant Design Pro + .Net5 WebApi:后端环境搭建-IdentityServer4(二)授权模式

    一.前言 先交代一下整个Demo项目结构: 一个认证服务(端口5000)IdentityServer4.Authentication 五个授权模式(两个控制台程序,三个MVC项目端口5001)文件夹G ...

  5. IdentityServer4(7)- 使用客户端认证控制API访问(客户端授权模式)

    一.前言 本文已更新到 .NET Core 2.2 本文包括后续的Demo都会放在github:https://github.com/stulzq/IdentityServer4.Samples (Q ...

  6. 微服务(入门四):identityServer的简单使用(客户端授权)

    IdentityServer简介(摘自Identity官网) IdentityServer是将符合规范的OpenID Connect和OAuth 2.0端点添加到任意ASP.NET核心应用程序的中间件 ...

  7. 【.NET Core项目实战-统一认证平台】第十一章 授权篇-密码授权模式

    [.NET Core项目实战-统一认证平台]开篇及目录索引 上篇文章介绍了基于Ids4客户端授权的原理及如何实现自定义的客户端授权,并配合网关实现了统一的授权异常返回值和权限配置等相关功能,本篇将介绍 ...

  8. Spring Cloud2.0之Oauth2环境搭建(授权码模式和密码授权模式)

    oauth2 server 微服务授权中心,    github源码  https://github.com/spring-cloud/spring-cloud-security 对微服务接口做一些权 ...

  9. 认证授权:IdentityServer4 - 各种授权模式应用

    前言: 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例 授权模式: 环境准备 a)调整项目结构如下:   b)调整cz.Id ...

随机推荐

  1. Net中实现HTML生成图片或PDF

    Net中实现HTML生成图片或PDF的几种方式 前段时间由于项目上的需求,要在.Net平台下实现把HTML内容生成图片或PDF文件的功能,特意在网上研究了几种方案,这里记录一下以备日后再次使用.当时想 ...

  2. csu 1770: 按钮控制彩灯实验

    1770: 按钮控制彩灯实验 Submit Page   Summary   Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 341 ...

  3. pandas之聚合运算

    通过聚合运算可以得到我们比较感兴趣的数据以方便处理 import pandas as pd import numpy as np # 先创建一组数据表DataFrame df = pd.DataFra ...

  4. 使用寄存器点亮LED(第2节)—寄存器映射代码讲解

    // 打开 GPIOB 端口的时钟 *( unsigned int * )0x40021018|= ( 1 << 4 ); // 配置PC2 IO口为通用推挽输出,速度为10M *( un ...

  5. JVM OOM异常会导致JVM退出吗?

    出处:  https://mp.weixin.qq.com/s/8j8YTcr2qhVActLGzOqe7Q  https://blog.csdn.net/h2604396739/article/de ...

  6. SpringBoot 第二篇:SpringBoot配置文件使用

    背景 项目跑起来,和以前相比,现在的配置文件能干什么?SpringBoot 项目的配置文件就是创建项目时,自带的 application.properties ,打开里面空空如也.这个文件里面的语法是 ...

  7. IDEA报错: Clone failed: Authentication failed for 'http://10.70.XXXXXXXXXXXXXXXXX'

    今天从git上导入公司的项目,总是报错Clone failed: Authentication failed for 'http://10.70.XXXXXXXXXXXXXX' 在网上百度了一下,大致 ...

  8. 解决django的后台管理界面添加中文内容乱码问题

    在使用django migrate功能时,默认数据库的字符集不是utf8. 是latin 1,然后在后台管理model时,不允许有中文字符插入 解决方案: 在使用migrate建库之前先把数据库建立起 ...

  9. 轻松搭建CAS 5.x系列(8)-在CAS Server增加双因素认证(DUO版)

    概述说明 为了让系统更加安全,很多登录会加入双因素认证.何为双因素,如果把登陆作为开一扇门的话,那就是在原来的锁上再加一把锁,第二锁用新的钥匙,这样安全系数就更加高了. CAS是通过账号名和密码来认证 ...

  10. javadoc 自动生成java帮助文档

    用法: javadoc [options] [packagenames] [sourcefiles] 选项: -public 仅显示 public 类和成员 -protected 显示 protect ...