IdentityServer4身份认证授权入门
一.简介
IdentityServer4 是为ASP.NET Core 系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证框架
特点:
1.认证服务
2.单点登录登出(SSO)
3.API访问控制
4.联合网关
5.专注于定制
6.成熟的开源系统
7.免费和商业支持
二.简单示例
1.创建ASP.NET Core 3.0 WebAPI项目
执行cmd命令:dotnet new webapi --name IdentityServerCenter
2.打开项目
执行cmd命令:code IdentityServerSimple 来打开VS Code
3.nuget 安装IdentityServer4
执行Ctrl+Shift+p键 打开Command Palette(命令选项卡)
输入>nuget Package Manager:Add Package
`输入IdentityServer4 选择3.1.0
安装完成后
4.执行命令:dotnet restore( 还原依赖项和工具包)
5.创建Config类
using System.Collections.Generic;
using IdentityServer4.Models; namespace IdentityServerCenter{
public class Config{
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>{new ApiResource("api","MyAPI")};
} public static IEnumerable<Client> GetClients()
{
return new List<Client>{
new Client{ClientId="client",AllowedGrantTypes=GrantTypes.ClientCredentials,
ClientSecrets={new Secret("secret".Sha256())},
AllowedScopes={"api"}
}};
}
}
}
6.配置Startup类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
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.GetResources()).AddInMemoryClients(Config.GetClients());
services.AddControllers();
} // 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.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseIdentityServer(); }
}
}
7.配置Progarm类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; namespace IdentityServerCenter
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
} public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseUrls("http://localhost:5000");
});
}
}
8.运行服务端项目:
执行命令:dotnet run
访问地址:http://localhost:5000/.well-known/openid-configuration
三.客户端集成IdentityServer
1.创建项目
执行cmd命令:dotnet new webapi --name ClientCredentialApi
2. 添加Package
执行命令:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
3.添加IdentityController类
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace ClientCredentialApi.Controllers{ [Route("identity")]
[Authorize]
public class IdentityController:ControllerBase{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(new {Msg="Success",Code=});
}
}
}
4.配置Startup类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; namespace ClientCredentialApi
{
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(); 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(); app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
5.配置Program类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; namespace ClientCredentialApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
} public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseUrls("http://localhost:5001");
});
}
}
6.运行项目
执行命令:dotnet restore dotnet run
7.输入:http://localhost:5001/identity
401:表示未授权
8.运行服务端和客户端
使用PostMan来获取Token
选择post请求
选择form-data
client_id:client client_secret:secret grant_type:client_credentials
9.通过Token来验证
请求地址:http://localhost:5001/identity
请求方式:get
Headers: key:Authorization value:Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ikt1Ni1YWk9HNWhYYUh3NHdWWGxwSXciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODA4MDYxODIsImV4cCI6MTU4MDgwOTc4MiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiYXBpIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsiYXBpIl19.A7Mj6xanZfZaAartfFNb3Z6unZRxOGSHgUufcyKFAhL5Ojy5GsXeFlZBTWundXKIC5SILWHoafWrOFvVNcGtH4CxDgUDhlyMpkCRBJyPaAInbLIFqlX9HJLqxzqwUa2Y6qVKtmjBE4WQ9fg4cZSNGviEiqBe2nk2T_U-RLF-y3OMZ6tZblpVZrMYsRiUiyjum3jRJBXRJOw1JaG13OLLrKoEIWX43qRtLZT_5bScqcDJmx4gmcTDeZZZrmsoeT4A7Sr_5hFx_UgwD1edoZiikeFRSvUJZAhLJfuFSR72xMAWSmmqq_H8B3Ed158y0aQb_mHgT8zbQZbHHhIEKD94jg
四.第三方ClientCredential模式调用
1.创建控制台项目
执行cmd命令:dotnet new console -n ThirdPartyDemo
2.添加IdentityModel包
执行cmd命令:dotnet add package IdentityModel
3.开始测试
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
} var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint, ClientId = "client",
ClientSecret = "secret",
Scope = "api"
}); if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json); 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(content);
}
错误解决:Versioning information could not be retrieved from theNuget package repository. Please try again later.
打开文件:C:\Users\Administrator\.vscode\extensions\jmrog.vscode-nuget-package-manager-1.1.6\out\src\actions\add-methods\fetchPackageVersions.js
API文档:http://docs.identityserver.io/en/latest/index.html
中文文档:http://www.identityserver.com.cn/
代码地址:https://github.com/CodeInterface/IdentityServerSimple/tree/Simple
IdentityServer4身份认证授权入门的更多相关文章
- [认证授权] 5.OIDC(OpenId Connect)身份认证授权(扩展部分)
在上一篇[认证授权] 4.OIDC(OpenId Connect)身份认证授权(核心部分)中解释了OIDC的核心部分的功能,即OIDC如何提供id token来用于认证.由于OIDC是一个协议族,如果 ...
- [认证授权] 4.OIDC(OpenId Connect)身份认证授权(核心部分)
0 目录 认证授权系列:http://www.cnblogs.com/linianhui/category/929878.html 1 什么是OIDC? 看一下官方的介绍(http://openid. ...
- Shiro身份认证授权原理
shiro在应用程序中的使用是用Subject为入口的, 最终subject委托给真正的管理者ShiroSecurityMannager Realm是Shiro获得身份认证信息和来源信息的地方(所以这 ...
- .net core gRPC与IdentityServer4集成认证授权
前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...
- .NetCore下使用IdentityServer4 & JwtBearer认证授权在CentOS Docker容器中运行遇到的坑及填坑
今天我把WebAPI部署到CentOS Docker容器中运行,发现原有在Windows下允许的JWTBearer配置出现了问题 在Window下我一直使用这个配置,没有问题 services.Add ...
- ASP.NET Core的无状态身份认证框架IdentityServer4
Identity Server 4是IdentityServer的最新版本,它是流行的OpenID Connect和OAuth Framework for .NET,为ASP.NET Core和.NE ...
- [认证授权] 5.OIDC(OpenId Connect)身份认证(扩展部分)
在上一篇[认证授权] 4.OIDC(OpenId Connect)身份认证(核心部分)中解释了OIDC的核心部分的功能,即OIDC如何提供id token来用于认证.由于OIDC是一个协议族,如果只是 ...
- .NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据
内容:本文带大家使用IdentityServer4进行对API授权保护的基本策略 作者:zara(张子浩) 欢迎分享,但需在文章鲜明处留下原文地址. 本文将要讲述如何使用IdentityServer4 ...
- 基于.NetCore3.1系列 ——认证授权方案之Swagger加锁
一.前言 在之前的使用Swagger做Api文档中,我们已经使用Swagger进行开发接口文档,以及更加方便的使用.这一转换,让更多的接口可以以通俗易懂的方式展现给开发人员.而在后续的内容中,为了对a ...
随机推荐
- 关于在vuejs中动态加载不确定数量和内容的组件的解决方案
在做一个门户项目的时候,客户要求需要进行私人化定制,每个人进入首页的时候可以自定义首页显示的版块 要在4.50个组件中显示随机N个组件按照每个人选定的顺序排列.需求说完了,接下来说说解决方案: htm ...
- $Noip2012\ Luogu1081$ 开车旅行 倍增优化$ DP$
Luogu Description Sol 1.发现对于每个城市,小A和小B的选择是固定的,可以预处理出来,分别记为ga[],gb[] 2.并且,只要知道了出发城市和出发天数,那么当前城市和小A,小B ...
- ASP.NET Core 中间件的几种实现方式
前言 ASP.NET Core 中 HTTP 管道使用中间件组合处理的方式, 换句人话来说, 对于写代码的人而言,一切皆中间件. 业务逻辑/数据访问/等等一切都需要以中间件的方式来呈现. 那么我们必须 ...
- 20行Python代码爬取王者荣耀全英雄皮肤
引言王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了.我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成. 准备工作 ...
- Go语言教程之结构体
Hello,大家好,我是小栈君,最近因为工作的事情延误了一点分享的进度,但是我会尽量抽时间分享关于IT干货知识,还希望大家能够持续关注"IT干货栈"哦. 闲话不多说,今天给大家继续 ...
- Yolo V3损失函数占个坑
https://blog.csdn.net/weixin_43384257/article/details/100974776目前来看讲的最清楚的博客 https://zhuanlan.zhihu.c ...
- 初识Activiti工作流
一.背景介绍 公司最近接了一个监狱AB门系统的项目,在对项目进行调研时,发现客户的关注点主要是在AB门流程这块,项目大部分功能都是审批流程和单据流动状态等.而之前公司的项目关于流程主要都是在表中设置状 ...
- window 10 安装Oracle odac 64位
下载地址:https://www.oracle.com/cn/database/technologies/windows/downloads.html 可以下载XCopy版,也可以继续往下看下载安装文 ...
- .NET为什么要使用异步(async)编程?⭐⭐⭐⭐⭐
.NET为什么要使用异步(async)编程? 有几点坐下笔记 ⭐⭐⭐⭐: 1. 同步方法 static void Main(string[] args) { Console.WriteLine($&q ...
- 深入理解es6中的Promise
https://www.jianshu.com/p/9e4af5b77253 https://zhuanlan.zhihu.com/p/30797777 https://segmentfault.co ...