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=200});
        }
    }
}

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

原文地址:https://www.cnblogs.com/vic-tory/p/12260373.html

时间: 2024-08-06 04:49:10

IdentityServer4身份认证授权入门的相关文章

nest.js + typeORM:身份认证,事务管理

知识点 jwt身份认证 md5加密 typeorm事务(transaction)的使用 本文会延续上一篇文章,继续实现login功能,并实现API的身份认证,查看全部源码. JWT身份认证 对与绝大多数应用程序来说,身份认证是必不可少的组成部分,而对用户的身份认证授权的策略和方法非常多,选用何种方法取决于项目的需求. passport是node.js中的一个比较流行的认证库,本项目Demo会使用passport-jwt策略来实现用户身份认证. JWT(Json Web Token)是一种用于双方

asp.net core 使用identityServer4的密码模式来进行身份认证(2) 认证授权原理

原文:asp.net core 使用identityServer4的密码模式来进行身份认证(2) 认证授权原理 前言:本文将会结合asp.net core 认证源码来分析起认证的原理与流程.asp.net core版本2.2 对于大部分使用asp.net core开发的人来说. 下面这几行代码应该很熟悉了. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { o

asp.net core 使用identityServer4的密码模式来进行身份认证(一)

原文:asp.net core 使用identityServer4的密码模式来进行身份认证(一) IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后端api的身份认证功能. 一 首先第一步使用Nuge包管理器下载IdentityServer4的包. 第二部,添加一个名叫Config的类. 这个类的作用是对一些api和client进行配置的. pub

超级狗是集软件授权、课件保护和身份认证于一身的加密狗。

超级狗是加密狗家族中最新一代软件保护和授权产品.它提供了强大的软件.课件防盗版功能以及灵活的软件授权功能,保护软件开发商的知识产权与核心技术,确保开发商的市场收入. 超级狗将软件保护与授权技术化繁为简.通过易于理解.易于上手的外壳保护工具.许可设计工具,以及在线授权工具,软件开发商可以轻松地实现高强度的软件保护和多种授权模式. 在保持SafeNet一贯高品质.高稳定性.高安全性的基础之上,超级狗还提供了基于时间.功能控制的许可模式,同时拥有更友好.直观的用户界面和更简单的操作流程. 超级狗可以帮

证明与计算(6): 身份认证与授权

目录: ** 0x00 引子 ** 0x01 用户名和密码 ** 0x02 密码管理器的基本原理 ** 0x03 多因素认证 ** 0x04 双因素认证(two-factor-auth)的基本原理. ** 0x05 [OpenID] vs [OAuth] ** 0x06 [IDToken] vs [JWT, JWS, JWE] 0x00 引子 每天,你使用用户名和密码登录网站. 每天,你使用手机验证码重置密码. 每天,你使用微信扫码登录其他软件. 每天,你使用微信授权第三方小程序访问你的个人信息

Kubernetes之(十五)身份认证,授权,准入控制

目录 Kubernetes之(十五)身份认证,授权,准入控制 ServiceAccount 创建serviceaccount 自定义serviceaccount 自建证书和账号进行访问apiserver RBAC简介 Kubernetes RBAC演示 RBAC的三种授权访问 Kubernetes之(十五)身份认证,授权,准入控制 API Server作为Kubernetes网关,是访问和管理资源对象的唯一入口,其各种集群组件访问资源都需要经过网关才能进行正常访问和管理.每一次的访问请求都需要进

Kubernetes身份认证和授权操作全攻略:上手操作Kubernetes授权

这是本系列文章中的第三篇,前两篇文章分别介绍了Kubernetes访问控制以及身份认证.本文将通过上手实践的方式,带你理解Kubernetes授权这一概念. 在文章正式开始之前,我们先快速回顾一下我们实操过程中的环境和场景.我们正在处理生产环境中的集群,其中每个部分都与命名空间相关联.现在,组里新来了一位同事叫Bob,我们在上篇教程中帮助Bob以engineering命名空间管理员的身份加入集群.并且他已经获得私钥以及签名证书来访问集群. 如果你还没有完成上述操作,请查看上篇教程,运行其中的命令

基于oauth授权框架其中获取令牌需要发送Http身份认证的请求

1.首先我们基于curl的请求参数示例: curl http://localhost:8080/oauth/token -X POST -u client:fucksecurity -d "grant_type=refresh_token&refresh_token=1a1fb46e-8ab4-4a3b-84c4-e70892eaa570"其中的 -u 表示的是身份认证的用户名和密码.后来尝试过Jquery的$.ajax的username和password去传这个两个对象,发现

【React全家桶入门之十】登录与身份认证

仔细想想,我们的后台系统还没有一个登录功能,太不靠谱,赶紧把防盗门安上! SPA的鉴权方式和传统的web应用不同:由于页面的渲染不再依赖服务端,与服务端的交互都通过接口来完成,而REASTful风格的接口提倡无状态(state less),通常不使用cookie和session来进行身份认证. 比较流行的一种方式是使用web token,所谓的token可以看作是一个标识身份的令牌.客户端在登录成功后可以获得服务端加密后的token,然后在后续需要身份认证的接口请求中在header中带上这个to