续IDS4建立Authorization server和Client

一、准备

创建一个名为QuickstartIdentityServer的ASP.NET Core Web 空项目(asp.net core 2.2),端口5000
创建一个名为Api的ASP.NET Core Web Api 项目(asp.net core 2.2),端口5001

二、定义服务端配置

1、NuGet命令行

NuGet命令行:Install-Package IdentityServer4

2、在QuickstartIdentityServer项目中添加一个Config.cs文件:

using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QuickstartIdentityServer
{
    public static class Config
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId()
            };
        }

        public static IEnumerable<ApiResource> ApiResources()
        {
            return new[]
            {
                new ApiResource("socialnetwork", "社交网络")
            };
        }
        public static IEnumerable<Client> Clients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "socialnetwork",
                    ClientSecrets = new [] { new Secret("secret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "socialnetwork" }
                }
            };
        }
        public static IEnumerable<TestUser> Users()
        {
            return new[]
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "[email protected]",
                    Password = "password"
                }
            };
        }
    }
}

3、注入ids4服务

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = services.AddIdentityServer()
           .AddDeveloperSigningCredential()
           .AddInMemoryIdentityResources(Config.GetIdentityResources())
           .AddInMemoryApiResources(Config.ApiResources())//配置资源
           .AddInMemoryClients(Config.Clients());//配置客户端
            // rest omitted
        }
        // 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.UseIdentityServer();//添加到管道中

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

三、定义Api端配置

1、通过nuget添加即可:

IdentityServer4.AccessTokenValidation

资源库配置identity server就需要对token进行验证, 这个库就是对access token进行验证的. 通过nuget安装.

2、配置

        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() //将认证服务添加到DI,配置"Bearer"作为默认方案
            .AddJsonFormatters();

            //注册IdentityServer
            services.AddAuthentication(config => {
                config.DefaultScheme = "Bearer"; //这个是access_token的类型,获取access_token的时候返回参数中的token_type一致
            }).AddIdentityServerAuthentication(option => {//将IdentityServer访问令牌验证处理程序添加到DI中以供身份验证服务使用
                option.ApiName = "socialnetwork"; //资源名称,认证服务注册的资源列表名称一致(该Api项目对应的IdentityServer的Api资源,与GetApiResources方法里面的Api名称对应),
                option.Authority = "http://localhost:5000"; //认证服务的url
                option.RequireHttpsMetadata = false; //是否启用https

            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication(); //将认证中间件添加到流水线中,以便在对主机的每次呼叫时自动执行认证
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

 3、添加WebApi资源服务器(就是拿到Token用来请求WebApi接口)

3.1、已有控制器添加[Authorize]特性,用来测试访问:这里注意要添加[Authorize]特性。用来做验证是否有权限的。没有的话,以上做的没有意义。需要引用命名空间:using Microsoft.AspNetCore.Authorization;

 3.2、在项目Api中新增接口文件IdentityController.cs,用于测试授权

如果你直接访问http://localhost:5001/identity ,你会得到一个401错误,因为调用这个接口需要凭证

这里设置一个Api接口,路由是"identity",跟传统的/controller/action访问路由不同,GET请求访问/identity即可

    [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 });
        }
    }

三、使用postman来测试接口

我们分别启动这两个项目,5000端口代表授权服务器,5001代表Api服务器
使用postman来测试调用

测试1(从授权服务器拿到token)

测试2(拿token去访问WebApi资源)

把access_token贴到Authorization Header的值里面, 前边要加上Bearer表示类型, 还有一个空格.

或者直接

注意: 测试出现这种情况是

是因为资源配置不一致:

图如下

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.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";
                });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

原文地址:https://www.cnblogs.com/fger/p/11029478.html

时间: 2024-08-01 03:27:35

续IDS4建立Authorization server和Client的相关文章

五、WebApi建立authorization server

一.服务端建立authorization server 1.安装 Install-Package identityserver4 2.编写配置类 //一.IDS4服务制定 public class Config { //1.定义API资源 public static IEnumerable<ApiResource> GetApis() //ApiResource是属于using IdentityServer4.Models;内的. { return new List<ApiResourc

使用Identity Server 4建立Authorization Server (1)

预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 本文内容基本完全来自于Identity Server 4官方文档: https://identityserver4.readthedocs.io/ 官方文档很详细的. 使用OAuth可以更安全, 这里我们的authorization server和web api 以及网站将分别独立运行. 建立authorization server 建立asp.net core 项目使用空模板. 项目建立后, 运行

OAuth2、OpenID Connect、IdentityServer建立Authorization Server简介

当我们在登录一些网站的时候,需要第三方的登录.比如,现在我们要登录简书https://www.jianshu.com/sign_in,我们使用微博登录,点击下方的一个微博的小按钮,就会出现这么一个地址https://api.weibo.com/oauth2/authorize?client_id=1881139527&redirect_uri=http%3A%2F%2Fwww.jianshu.com%2Fusers%2Fauth%2Fweibo%2Fcallback&response_ty

使用Identity Server 4建立Authorization Server (2)

第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一个简单的Identity Server. 接下来继续: 建立Web Api项目 如图可以在同一个解决方案下建立一个web api项目: (可选)然后修改webapi的launchSettings.json, 我习惯使用控制台, 所以把IISExpress相关的都删掉, 并且把端口改成5001: { "profiles": { "WebApi": {

使用Identity Server 4建立Authorization Server (5)

预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二部分: http://www.cnblogs.com/cgzl/p/7788636.html 第三部分: http://www.cnblogs.com/cgzl/p/7793241.html 第四部分: http://www.cnblogs.com/cgzl/p/7795121.html 之前的配置

TCP连接的状态与关闭方式及其对Server与Client的影响

1. TCP连接的状态 首先介绍一下TCP连接建立与关闭过程中的状态.TCP连接过程是状态的转换,促使状态发生转换的因素包括用户调用.特定数据包以及超时等,具体状态如下所示: CLOSED:初始状态,表示没有任何连接.LISTEN:Server端的某个Socket正在监听来自远方的TCP端口的连接请求.SYN_SENT:发送连接请求后等待确认信息.当客户端Socket进行Connect连接时,会首先发送SYN包,随即进入SYN_SENT状态,然后等待Server端发送三次握手中的第2个包.SYN

OWIN OAuth 2.0 Authorization Server

OWIN OAuth 2.0 Authorization Server 源码在上面的地址中可以下载 打开客户端页面http://localhost:38500/ 客户端代码引用了DotNetOpenAuth.OAuth2 public class HomeController : Controller { private WebServerClient _webServerClient; public ActionResult Index() { ViewBag.AccessToken = Re

TCP连接的状态与关闭方式,及其对Server与Client的影响

1. TCP连接的状态 首先介绍一下TCP连接建立与关闭过程中的状态.TCP连接过程是状态的转换,促使状态发生转换的因素包括用户调用.特定数据包以及超时等,具体状态如下所示: CLOSED:初始状态,表示没有任何连接. LISTEN:Server端的某个Socket正在监听来自远方的TCP端口的连接请求. SYN_SENT:发送连接请求后等待确认信息.当客户端Socket进行Connect连接时,会首先发送SYN包,随即进入SYN_SENT状态,然后等待Server端发送三次握手中的第2个包.

distributed programming---lab1(basic communication of server and client)

socket() creates an endpoint for communication and returns a file        descriptor that refers to that endpoint. The lab is about basic communication of server and client. The server is iterative server which only serves one client at a time. The so