转自:https://www.cnblogs.com/hyqq/p/14138024.html;侵删。

Client Credentials

客户端应用不代表用户,客户端应用本身就相当于资源所有者

通常用于机器对机器的通信

客户端也需要身份认证

详细查看https://oauth.net/2/grant-types/client-credentials/

安装identityserver4模板

dotnet new -i identityserver4.templates //下载identityserver4模板
dotnet new is4inmem --name Idp //创建一个is4inmem模板的项目 名字为Idp

Config代码

using IdentityServer4.Models;
using System.Collections.Generic; namespace Idp
{
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
}; public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("scope1"),
}; public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("api1","#api1")
{
//!!!重要
Scopes = { "scope1"}
}
}; public static IEnumerable<Client> Clients =>
new Client[]
{
// m2m client credentials flow client
new Client
{
ClientId = "console client",
ClientName = "Client Credentials Client", AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) }, AllowedScopes = { "scope1" }
},
};
}
}

startup代码

using IdentityServerHost.Quickstart.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; namespace Idp
{
public class Startup
{
public IWebHostEnvironment Environment { get; }
public IConfiguration Configuration { get; } public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//注册IdentityServer
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true; // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true;
})
//用户
.AddTestUsers(TestUsers.Users); // in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
//添加API资源
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
} public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}

创建一个控制台应用 consoleclient

安装identitymodel库

Program代码

using IdentityModel.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks; namespace consoleclient
{
class Program
{
static async Task Main(string[] args)
{
//
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
//请求accesstoken
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "console client",
ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",
Scope = "scope1"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.ReadKey();
}
}
}

启动2个项目 监听tokenresponse

创建空的web项目 添加Controller文件夹 添加IdentityController控制器

添加Microsoft.AspNetCore.Authentication.JwtBearer库

IdentityController代码

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq; namespace scope1
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type,c.Value} );
}
}
}

Startup代码

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; namespace scope1
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//IdentityServer地址
options.Authority = "http://localhost:5000";
//对应Idp中ApiResource的Name
options.Audience = "api1";
//不使用https
options.RequireHttpsMetadata = false;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//身份验证
app.UseAuthentication();
//授权
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

继续修改consoleclient项目的Program.cs

using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks; namespace consoleclient
{
class Program
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
if (!disco.IsError)
{
//请求accesstoken
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "console client",
ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",
Scope = "scope1"
});
if (!tokenResponse.IsError)
{
//使用请求accesstoken访问被保护的资源
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("http://localhost:5001/api/Identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
}
}
}
}

启动程序

打印结果

Identityserver4 ClientCredentials授权的更多相关文章

  1. IdentityServer4 自定义授权模式

    IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode.ClientCredentials.Password.RefreshToken.DeviceCode), ...

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

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

  3. IdentityServer4 (3) 授权码模式(Authorization Code)

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

  4. 一看就懂的IdentityServer4认证授权设计方案

    查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...

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

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

  6. Swagger+IdentityServer4测试授权验证

    1.Bearer授权操作,添加如下代码 services.AddSwaggerGen(options => { options.AddSecurityDefinition("Beare ...

  7. IdentityServer4 QuckStart 授权与自定义Claims

    最近在折腾IdentityServer4,为了简单,直接使用了官方给的QuickStart示例项目作为基础进行搭建.有一说一,为了保护一个API,感觉花费的时间比写一个API还要多. 本文基于ASP. ...

  8. IdentityServer4系列 | 授权码模式

    一.前言 在上一篇关于简化模式中,通过客户端以浏览器的形式请求IdentityServer服务获取访问令牌,从而请求获取受保护的资源,但由于token携带在url中,安全性方面不能保证.因此,我们可以 ...

  9. 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理(内容可能会有部分,推荐看源视频学习) 前言 由于之前的博客都是基于其他的博客进行开发,现在重新整理一下方便 ...

  10. Asp.NetCoreWebApi图片上传接口(二)集成IdentityServer4授权访问(附源码)

    写在前面 本文地址:http://www.cnblogs.com/yilezhu/p/9315644.html 作者:yilezhu 上一篇关于Asp.Net Core Web Api图片上传的文章使 ...

随机推荐

  1. vue编辑修改,点击取消操作时,table内的内容不变

    1.父组件内  2.子组件内(使用JSON.parse(JSON.stringify(xxx值)))  进行深拷贝

  2. ABAP 动态内表 实例展示以及代码Demo

    因根据查询条件展示的报表列数不一定一致,因此采用动态内表的方式进行处理 这里写了一个简单的Demo记录一下 效果如下图: 一般来说通过选择屏幕来控制列的,我这里就简单处理,直接对内表赋予相关值,包括相 ...

  3. ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台

    ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台   ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台 Kint ...

  4. react-router 路由 入门必看

    如果您已经入门reactjs,请绕道~ 这篇博客只适合初学者,初学reactjs的时候,如果你不会webpack,相信很多人都会被官方的例子绕的晕头转向. ES6的例子也会搞死一批入门者.之前一直用的 ...

  5. idea引入ojdbc包报错

    网上下载或者让同事传两个jar过来,ojdbc6-11.2.0.7.0.jar 以及jconn3.0.jar 放入同一个文件夹中: 在此文件夹中cmd如下:回车,进入cmd控制台. 输入如下两个命令: ...

  6. iOS 15 UI适配

    1. UINavigationBar 在iOS 15中,UINavigationBar默认为透明.在滑动时会有模糊效果.如果想要一直就是模糊效果,可以通过改变scrollEdgeAppearance属 ...

  7. grpc start with python

    pip install grpcio grpcio-tools syntax = "proto3"; service FutureData { rpc GetTick(ReqTic ...

  8. libev中的gcc内嵌函数

    在学习libev的过程中,遇到了大量的gcc内嵌函数,大多是为了提升性能而使用的,这里做一个汇总和介绍,并会持续更新 1.__builtin_expect:该函数是gcc引入的,为的是让程序员讲最有可 ...

  9. rabbitMq安装 - docker

    安装rabbitmq 参考网站:https://www.rabbitmq.com/download.html 方式一: 获取rabbit镜像: docker pull rabbitmq:managem ...

  10. vue搭建项目iview+axios+less

    项目地址:https://github.com/CinderellaStory/vue-iview-project vue搭建项目壳子已安装:iview.axios.less 已有界面:登录.左侧菜单 ...