(1)identityserver4授权服务器端

public static class Config

{

public static IEnumerable<IdentityResource> GetIdentityResources()

{

return new IdentityResource[]

{

new IdentityResources.OpenId(),

new IdentityResources.Profile(),

new IdentityResources.Email(),

new IdentityResources.Phone(),

new IdentityResources.Address(),

};

}

public static IEnumerable<ApiResource> GetApis()

{

return new ApiResource[]

{

new ApiResource("api1", "My API #1")

};

}

public static IEnumerable<Client> GetClients()

{

return new[]

{

new Client

{

ClientId="mvc client",

ClientName="ASP.NET Core MVC Client",

AllowedGrantTypes=GrantTypes.CodeAndClientCredentials,

ClientSecrets={new Secret( "mvc secret".Sha256())},

RedirectUris={"http://localhost:5002/signin-oidc"},

FrontChannelLogoutUri="http://localhost:5002/signout-oidc",

PostLogoutRedirectUris={"http://localhost:5002/signout-callback-oidc"},

AlwaysIncludeUserClaimsInIdToken=true,//将用户所有的claims包含在IdToken内

AllowOfflineAccess=true,//offline_access,其实指的是能否用refreshtoken重新申请令牌

AllowedScopes =

{

"api1",

IdentityServerConstants.StandardScopes.OpenId,

IdentityServerConstants.StandardScopes.Profile,

IdentityServerConstants.StandardScopes.Address,

IdentityServerConstants.StandardScopes.Phone,

IdentityServerConstants.StandardScopes.Email

}

}

};

}

}

(2)客户端,还是需要安装IdentityModel库,

startup.csConfigurServices一节,需要做如下添加

//关闭默认映射,否则它可能修改从授权服务返回的各种claim属性

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

//添加认证服务,并设置其有关选项

services.AddAuthentication(options =>

{

//客户端应用设置使用"Cookies"进行认证

options.DefaultScheme =CookieAuthenticationDefaults.AuthenticationScheme ;

//identityserver4设置使用"oidc"进行认证

options.DefaultChallengeScheme =OpenIdConnectDefaults.AuthenticationScheme ;

}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)

//对使用的OpenIdConnect进行设置,此设置与Identityserver的config.cs中相应client配置一致才可能登录授权成功

.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options=> {

options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

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

options.RequireHttpsMetadata = false;

options.ClientId = "mvc client";

options.ClientSecret = "mvc secret";

options.SaveTokens = true;

options.ResponseType = "code";

options.Scope.Clear();

options.Scope.Add("api1");

options.Scope.Add(OidcConstants.StandardScopes.OpenId);//"openid"

options.Scope.Add(OidcConstants.StandardScopes.Profile);//"profile"

options.Scope.Add(OidcConstants.StandardScopes.Address);

options.Scope.Add(OidcConstants.StandardScopes.Email);

options.Scope.Add(OidcConstants.StandardScopes.Phone);

// 与identity server的AllowOfflineAccess=true,对应。offline_access,指的是能否用refreshtoken重新申请令牌

options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);

});

Confiure一节,app.UseMvc之前添加如下内容:

app.UseAuthentication();

然后,在controller中使用时,按如下方式:    通常需如下引用

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Net.Http;

using System.Threading.Tasks;

using IdentityModel.Client;

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authentication.OpenIdConnect;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;

using Microsoft.IdentityModel.Protocols.OpenIdConnect;

using MvcClient.Models;

//获取AccessToken、IdToken、RefreshToken时:

[Authorize]

public async Task<IActionResult> Privacy()

{

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

var idToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken);

var refreshToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

var authorizationCode = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.Code);

ViewData["idToken"] = idToken;

ViewData["refreshToken"] = refreshToken;

ViewData["accessToken"] = accessToken;

return View();

}

//访问Api资源时

public async Task<IActionResult> AccessApi()

{

var client = new HttpClient();

var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");

ViewData["disco"] = disco.Error;

if (disco.IsError)

{

ViewData["disco"] = disco.Error;

return View();

}

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

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/values");

if (!response.IsSuccessStatusCode)

{

ViewData["response_error"] = response.StatusCode;

return View();

}

ViewData["response-content"] = await response.Content.ReadAsStringAsync();

return View();

}

从客户端及identityserver4登出时:

public async Task<IActionResult> Logout()

{

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

return View();

}

如果登出需要跳转回到客户端应用网站,则需在将IdentityServer4的命名空间IdentityServer4.Quickstart.UI下的AccountOptions类中

public static bool AutomaticRedirectAfterSignOut = true;

这样,从identityserver登出后,将自动跳转到客户应用页面。

最新文章

  1. Spring和Mybatis整合,配置文件
  2. JavaScript闭包模型
  3. Android添加快捷方式
  4. HSV与RGB颜色空间的转换
  5. for循环与for循环嵌套
  6. 点亮第一个LED灯
  7. centos 常用命令
  8. JS对URL字符串进行编码/解码分析
  9. Swift实战-小QQ(第2章):QQ侧滑菜单
  10. zoj 3232 It&#39;s not Floyd Algorithm(强联通分量,缩点)
  11. jsp注释方式
  12. Web NFC API
  13. SWTBOK測试实践系列(4) -- 软件測试技术的黑白之道
  14. java学习之匿名内部类与包装类
  15. 2017-2-24 C#基础 for循环的嵌套
  16. cookie和session有什么区别,请你谈谈cookie的缺点
  17. Java 线程池原理分析
  18. python输入
  19. MT【240】6*6放黑白子
  20. LeetCode题解之Rotated Digits

热门文章

  1. 语义化标签&amp;唯一性标签
  2. java 8 list的stream操作 list中的对象中的某一个成员取出转为该成员的list,以及对象过滤,筛选某个属性后的成员
  3. SSL 证书格式普及,PEM、CER、JKS、PKCS12
  4. vc code js 配置
  5. codeforces- Shortest path of the king
  6. Python 爬取 热词并进行分类数据分析-[热词分类+目录生成]
  7. 学习之学习--混沌大学商学院--第一课--HHR计划
  8. 机器学习之SVM多分类
  9. redis-key管理
  10. PAT A1131 Subway Map