IdentityServer4系列 | 授权码模式

访问令牌请求

(1)用户访问第三方应用,第三方应用将用户导向认证服务器

  (用户的操作:用户访问https://client.example.com/cb跳转到登录地址,选择授权服务器方式登录)

在授权开始之前,它首先生成state参数(随机字符串)。client端将需要存储这个(cookie,会话或其他方式),以便在下一步中使用。

GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz

        &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1

HTTP/1.1 Host: server.example.com

生成的授权URL如上所述(如上),请求这个地址后重定向访问授权服务器,其中 response_type参数为code,表示授权类型,返回code授权码。

参数 是否必须 含义

response_type 必需 表示授权类型,此处的值固定为"code"

client_id 必需 客户端ID

redirect_uri 可选 表示重定向的URI

scope 可选 表示授权范围。

state 可选 表示随机字符串,可指定任意值,认证服务器会返回这个值

(2)假设用户给予授权,认证服务器将用户导向第三方应用事先指定的重定向URI,同时带上一个授权码

HTTP/1.1 302 Found

Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz

参数 含义

code 表示授权码,必选项。该码的有效期应该很短,通常设为10分钟,客户端只能使用该码一次,否则会被授权服务器拒绝。该码与客户端ID和重定向URI,是一一对应关系。

state 如果客户端的请求中包含这个参数,认证服务器的回应也必须一模一样包含这个参数。

(3)第三方应用收到授权码,带上上一步时的重定向URI,向认证服务器申请访问令牌。这一步是在第三方应用的后台的服务器上完成的,对用户不可见。

POST /token HTTP/1.1

Host: server.example.com

Authorization: Bearer czZCaGRSa3F0MzpnWDFmQmF0M2JW

Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA

&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

参数 含义

grant_type 表示使用的授权模式,必选项,此处的值固定为"authorization_code"。

code 表示上一步获得的授权码,必选项。

redirect_uri 表示重定向URI,必选项,且必须与步骤1中的该参数值保持一致。

client_id 表示客户端ID,必选项。

(4)认证服务器核对了授权码和重定向URI,确认无误后,向第三方应用发送访问令牌(Access Token)和更新令牌(Refresh token)

HTTP/1.1 200 OK

    Content-Type: application/json;charset=UTF-8

    Cache-Control: no-store

    Pragma: no-cache

    {

      "access_token":"2YotnFZFEjr1zCsicMWpAA",

      "token_type":"Bearer",

      "expires_in":3600,

      "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",

      "example_parameter":"example_value"

    }

参数 含义

access_token 表示访问令牌,必选项。

token_type 表示令牌类型,该值大小写不敏感,必选项,可以是Bearer类型或mac类型。

expires_in 表示过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。

refresh_token 表示更新令牌,用来获取下一次的访问令牌,可选项。

scope 表示权限范围,如果与客户端申请的范围一致,此项可省略。

(5) 访问令牌过期后,刷新访问令牌

POST /token HTTP/1.1

Host: server.example.com

Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW

Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA

参数 含义

granttype 表示使用的授权模式,此处的值固定为"refreshtoken",必选项。

refresh_token 表示早前收到的更新令牌,必选项。

scope 表示申请的授权范围,不可以超出上一次申请的范围,如果省略该参数,则表示与上一次一致。

三、实践

在示例实践中,我们将创建一个授权访问服务,定义一个MVC客户端,MVC客户端通过IdentityServer上请求访问令牌,并使用它来访问API。

3.1 搭建 Authorization Server 服务

搭建认证授权服务

3.1.1 安装Nuget包

IdentityServer4 程序包

3.1.2 配置内容

建立配置内容文件Config.cs

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("code_scope1")

    };

    public static IEnumerable<ApiResource> ApiResources =>

        new ApiResource[]

    {

        new ApiResource("api1","api1")

        {

            Scopes={ "code_scope1" },

            UserClaims={JwtClaimTypes.Role},  //添加Cliam 角色类型

            ApiSecrets={new Secret("apipwd".Sha256())}

        }

    };

    public static IEnumerable<Client> Clients =>

        new Client[]

    {

        new Client

        {

            ClientId = "code_client",

            ClientName = "code Auth",

            AllowedGrantTypes = GrantTypes.Code,

            RedirectUris ={

                "http://localhost:5002/signin-oidc", //跳转登录到的客户端的地址

            },

            // RedirectUris = {"http://localhost:5002/auth.html" }, //跳转登出到的客户端的地址

            PostLogoutRedirectUris ={

                "http://localhost:5002/signout-callback-oidc",

            },

            ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },

            AllowedScopes = {

                IdentityServerConstants.StandardScopes.OpenId,

                IdentityServerConstants.StandardScopes.Profile,

                "code_scope1"

            },

            //允许将token通过浏览器传递

            AllowAccessTokensViaBrowser=true,

            // 是否需要同意授权 (默认是false)

            RequireConsent=true

        }

    };

}

RedirectUris : 登录成功回调处理的客户端地址,处理回调返回的数据,可以有多个。

PostLogoutRedirectUris :跳转登出到的客户端的地址。

这两个都是配置的客户端的地址,且是identityserver4组件里面封装好的地址,作用分别是登录,注销的回调

因为是授权码授权的方式,所以我们通过代码的方式来创建几个测试用户。

新建测试用户文件TestUsers.cs

    public class TestUsers

    {

        public static List<TestUser> Users

        {

            get

            {

                var address = new

                {

                    street_address = "One Hacker Way",

                    locality = "Heidelberg",

                    postal_code = 69118,

                    country = "Germany"

                };

                return new List<TestUser>

                {

                    new TestUser

                    {

                        SubjectId = "1",

                        Username = "i3yuan",

                        Password = "123456",

                        Claims =

                        {

                            new Claim(JwtClaimTypes.Name, "i3yuan Smith"),

                            new Claim(JwtClaimTypes.GivenName, "i3yuan"),

                            new Claim(JwtClaimTypes.FamilyName, "Smith"),

                            new Claim(JwtClaimTypes.Email, "i3yuan@email.com"),

                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),

                            new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),

                            new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)

                        }

                    }

                };

            }

        }

    }

返回一个TestUser的集合。

通过以上添加好配置和测试用户后,我们需要将用户注册到IdentityServer4服务中,接下来继续介绍。

3.1.3 注册服务

在startup.cs中ConfigureServices方法添加如下代码:

        public void ConfigureServices(IServiceCollection services)

        {

            var builder = services.AddIdentityServer()

              .AddTestUsers(TestUsers.Users); //添加测试用户

            // in-memory, code config

            builder.AddInMemoryIdentityResources(Config.IdentityResources);

            builder.AddInMemoryApiScopes(Config.ApiScopes);

            builder.AddInMemoryApiResources(Config.ApiResources);

            builder.AddInMemoryClients(Config.Clients);

            // not recommended for production - you need to store your key material somewhere secure

            builder.AddDeveloperSigningCredential();

            services.ConfigureNonBreakingSameSiteCookies();

        }

3.1.4 配置管道

在startup.cs中Configure方法添加如下代码:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseIdentityServer();

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapDefaultControllerRoute();

            });

        }

以上内容是快速搭建简易IdentityServer项目服务的方式。

这搭建 Authorization Server 服务跟上一篇简化模式有何不同之处呢?

在Config中配置客户端(client)中定义了一个AllowedGrantTypes的属性,这个属性决定了Client可以被哪种模式被访问,GrantTypes.Code为授权码模式。所以在本文中我们需要添加一个Client用于支持授权码模式(Authorization Code)。

3.2 搭建API资源

实现对API资源进行保护

3.2.1 快速搭建一个API项目

3.2.2 安装Nuget包

IdentityServer4.AccessTokenValidation 包

3.2.3 注册服务

在startup.cs中ConfigureServices方法添加如下代码:

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddControllersWithViews();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

        services.AddAuthentication("Bearer")

          .AddIdentityServerAuthentication(options =>

          {

              options.Authority = "http://localhost:5001";

              options.RequireHttpsMetadata = false;

              options.ApiName = "api1";

              options.ApiSecret = "apipwd"; //对应ApiResources中的密钥

          });

    }

AddAuthentication把Bearer配置成默认模式,将身份认证服务添加到DI中。

AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份认证服务使用。

3.2.4 配置管道

在startup.cs中Configure方法添加如下代码:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }   

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapDefaultControllerRoute();

            });

        }

UseAuthentication将身份验证中间件添加到管道中;

UseAuthorization 将启动授权中间件添加到管道中,以便在每次调用主机时执行身份验证授权功能。

3.2.5 添加API资源接口

[Route("api/[Controller]")]

[ApiController]

public class IdentityController:ControllerBase

{

    [HttpGet("getUserClaims")]

    [Authorize]

    public IActionResult GetUserClaims()

    {

        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });

    }

}

在IdentityController 控制器中添加 [Authorize] , 在进行请求资源的时候,需进行认证授权通过后,才能进行访问。

3.3 搭建MVC 客户端

实现对客户端认证授权访问资源

3.3.1 快速搭建一个MVC项目

3.3.2 安装Nuget包

IdentityServer4.AccessTokenValidation 包

3.3.3 注册服务

要将对 OpenID Connect 身份认证的支持添加到MVC应用程序中。

在startup.cs中ConfigureServices方法添加如下代码:

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddControllersWithViews();

        services.AddAuthorization();

        services.AddAuthentication(options =>

            {

                options.DefaultScheme = "Cookies";

                options.DefaultChallengeScheme = "oidc";

            })

              .AddCookie("Cookies")  //使用Cookie作为验证用户的首选方式

              .AddOpenIdConnect("oidc", options =>

              {

                  options.Authority = "http://localhost:5001";  //授权服务器地址

                  options.RequireHttpsMetadata = false;  //暂时不用https

                  options.ClientId = "code_client";

                  options.ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A";

                  options.ResponseType = "code"; //代表Authorization Code

                  options.Scope.Add("code_scope1"); //添加授权资源

                  options.SaveTokens = true; //表示把获取的Token存到Cookie中

                  options.GetClaimsFromUserInfoEndpoint = true;

              });

        services.ConfigureNonBreakingSameSiteCookies();

    }

AddAuthentication注入添加认证授权,当需要用户登录时,使用 cookie 来本地登录用户(通过“Cookies”作为DefaultScheme),并将 DefaultChallengeScheme 设置为“oidc”,

使用 AddCookie 添加可以处理 cookie 的处理程序。

在AddOpenIdConnect用于配置执行 OpenID Connect 协议的处理程序和相关参数。Authority表明之前搭建的 IdentityServer 授权服务地址。然后我们通过ClientId、ClientSecret,识别这个客户端。 SaveTokens用于保存从IdentityServer获取的token至cookie,ture标识ASP.NETCore将会自动存储身份认证session的access和refresh token。

3.3.4 配置管道

然后要确保认证服务执行对每个请求的验证,加入UseAuthentication和UseAuthorization到Configure中,在startup.cs中Configure方法添加如下代码:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("/Home/Error");

            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapControllerRoute(

                    name: "default",

                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });

        }

UseAuthentication将身份验证中间件添加到管道中;

UseAuthorization 将启动授权中间件添加到管道中,以便在每次调用主机时执行身份验证授权功能。

3.3.5 添加授权

在HomeController控制器并添加[Authorize]特性到其中一个方法。在进行请求的时候,需进行认证授权通过后,才能进行访问。

        [Authorize]

        public IActionResult Privacy()

        {

            ViewData["Message"] = "Secure page.";

            return View();

        }

还要修改主视图以显示用户的Claim以及cookie属性。

@using Microsoft.AspNetCore.Authentication

<h2>Claims</h2>

<dl>

    @foreach (var claim in User.Claims)

    {

        <dt>@claim.Type</dt>

        <dd>@claim.Value</dd>

    }

</dl>

<h2>Properties</h2>

<dl>

    @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)

    {

        <dt>@prop.Key</dt>

        <dd>@prop.Value</dd>

    }

</dl>

访问 Privacy 页面,跳转到认证服务地址,进行账号密码登录,Logout 用于用户的注销操作。

3.3.6 添加资源访问

在HomeController控制器添加对API资源访问的接口方法。在进行请求的时候,访问API受保护资源。

        /// <summary>

        /// 测试请求API资源(api1)

        /// </summary>

        /// <returns></returns>

        public async Task<IActionResult> getApi()

        {

            var client = new HttpClient();

            var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

            if (string.IsNullOrEmpty(accessToken))

            {

                return Json(new { msg = "accesstoken 获取失败" });

            }

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            var httpResponse = await client.GetAsync("http://localhost:5003/api/identity/GetUserClaims");

            var result = await httpResponse.Content.ReadAsStringAsync();

            if (!httpResponse.IsSuccessStatusCode)

            {

                return Json(new { msg = "请求 api1 失败。", error = result });

            }

            return Json(new

            {

                msg = "成功",

                data = JsonConvert.DeserializeObject(result)

            });

        }

亚马逊测评 www.yisuping.com

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,137评论 6 511
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,824评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,465评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,131评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,140评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,895评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,535评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,435评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,952评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,081评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,210评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,896评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,552评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,089评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,198评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,531评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,209评论 2 357

推荐阅读更多精彩内容