一、服务器

Client设置:

  new Client
{
ClientId = "mvc1",
ClientName = "后台管理MVC客户端",
ClientSecrets = { new Secret("mvc1".Sha256()) }, AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AllowOfflineAccess = true,
RequireConsent = false,
RedirectUris = { $"{ClientUrl}/signin-oidc",$"{LocalClientUrl}/signin-oidc"},
PostLogoutRedirectUris = { $"{ClientUrl}/signout-callback-oidc",$"{LocalClientUrl}/signout-callback-oidc"}, AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"IdServerAdmin_API"
}, AlwaysIncludeUserClaimsInIdToken = true
}

Startup.cs:

        /// <summary>
/// 设置认证服务器
/// </summary>
/// <param name="services"></param>
private void SetIdentityServer(IServiceCollection services)
{
#region 认证服务器
var ServerUrl = Configuration.GetSection("AppSetting:ServerUrl").Value;
var connectionString = Configuration.GetSection("AppSetting:ConnectionString").Value; //配置AccessToken的加密证书
var rsa = new RSACryptoServiceProvider();
//从配置文件获取加密证书
rsa.ImportCspBlob(Convert.FromBase64String(Configuration["AppSetting:SigningCredential"]));
var idServer = services.AddIdentityServer(options => {
options.IssuerUri = ServerUrl;
options.PublicOrigin = ServerUrl; options.Discovery.ShowApiScopes = true;
options.Discovery.ShowClaims = true; options.Events.RaiseSuccessEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseErrorEvents = true; });
//设置加密证书
idServer.AddSigningCredential(new RsaSecurityKey(rsa));
idServer.AddInMemoryApiResources(Config.GetApiResources());
idServer.AddInMemoryIdentityResources(Config.GetIdentityResources());
idServer.AddInMemoryClients(Config.GetClients()); services.AddTransient<IMyUserStore, MyUserStore>();
services.AddTransient<IProfileService, MyProfile>();
services.AddTransient<IResourceOwnerPasswordValidator, MyUserValidator>(); #endregion
}

  

 public class MyProfile : IProfileService
{
private readonly IMyUserStore _myUserStore;
public MyProfile(IMyUserStore myUserStore)
{
_myUserStore = myUserStore;
} public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var subjectId = context.Subject.GetSubjectId();
var user = _myUserStore.GetUserById(subjectId); var claims = new List<Claim>
{
new Claim("role", user.Role),
new Claim("userguid", user.SubjectId),
new Claim("abc", "这是自定义的值。……。。…。……。……")
}; var q = context.RequestedClaimTypes;
context.AddRequestedClaims(claims);
context.IssuedClaims.AddRange(claims); return Task.FromResult();
} public Task IsActiveAsync(IsActiveContext context)
{
var user = _myUserStore.GetUserById(context.Subject.GetSubjectId());
context.IsActive = (user != null); return Task.FromResult();
}
}
 public interface IMyUserStore
{
JUser Find(string username, string userpass);
JUser GetUserById(string subjectId);
} public class MyUserStore : IMyUserStore
{
readonly IOptions<AppSetting> _options;
readonly IMemoryCache _memoryCache; private const string CACHENAME = "MyUserStore"; public MyUserStore(IOptions<AppSetting> options, IMemoryCache m_memoryCache)
{
_options = options;
_memoryCache = m_memoryCache;
} public List<JUser> GetList(bool reload=true)
{
if (reload)
{
_memoryCache.Remove(CACHENAME);
} List<JUser> list;
if (!_memoryCache.TryGetValue(CACHENAME, out list)){
using(MySqlConnection conn = new MySqlConnection(_options.Value.ConnectionString))
{
list = conn.Query<JUser>("select * from juser").ToList(); //添加超级用户
JUser jc = new JUser()
{
UserName = _options.Value.SuperUserName,
UserPass = StringHelper.GetMd5(_options.Value.SuperPassword),
SubjectId = "a36005e2-5984-41f5-aa91-8e93b479d88e",
Role = "IdServerAdmin"
}; list.Add(jc);
}
_memoryCache.Set(CACHENAME, list);
}
return list;
} public JUser Find(string username, string userpass)
{
var list = GetList();
return list.SingleOrDefault(p => p.UserName == username && p.UserPass == StringHelper.GetMd5(userpass));
} public JUser GetUserById(string subjectId)
{
var list = GetList();
return list.SingleOrDefault(p => p.SubjectId == subjectId);
}
 public class MyUserValidator : IResourceOwnerPasswordValidator
{
readonly IMyUserStore _myUserStore; public MyUserValidator(IMyUserStore myUserStore)
{
_myUserStore = myUserStore;
} public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var q = _myUserStore.Find(context.UserName, context.Password); if (q != null)
{
//验证成功
//使用subject可用于在资源服务器区分用户身份等等
//获取:资源服务器通过User.Claims.Where(l => l.Type == "sub").FirstOrDefault();
var claims = new List<Claim>();
claims.Add(new Claim("role", q.Role));
claims.Add(new Claim("userguid", q.SubjectId)); context.Result = new GrantValidationResult(subject: $"{q.SubjectId}", authenticationMethod: "custom", claims: claims.AsEnumerable());
}
else
{
//验证失败
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "无效的用户凭证");
}
return Task.FromResult();
}
}

二、客户端:

  /// <summary>
/// 设置认证客户端
/// </summary>
/// <param name="services"></param>
private void SetIdentityClient(IServiceCollection services)
{
var ServerUrl = Configuration.GetSection("AppSetting:ServerUrl").Value;
var client_id = Configuration.GetSection("AppSetting:SuperClientId").Value;
var cient_secret = Configuration.GetSection("AppSetting:SuperClientSecret").Value; //services.Configure<MvcOptions>(options =>
//{
// // Set LocalTest:skipSSL to true to skip SSL requrement in
// // debug mode. This is useful when not using Visual Studio.
// options.Filters.Add(new RequireHttpsAttribute());
//}); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var idClient = services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SignOutScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // cookie middle setup above
options.Authority = ServerUrl; // 认证服务器
options.RequireHttpsMetadata = true; // SSL Https模式
options.ClientId = client_id; // 客户端(位于认证服务器)
options.ClientSecret = cient_secret; // 客户端(位于认证服务器)
options.ResponseType = "code id_token"; // means Hybrid flow (id + access token) options.GetClaimsFromUserInfoEndpoint = false;
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
}; options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("IdServerAdmin_API"); options.Events = new OpenIdConnectEvents()
{
OnMessageReceived = (context) =>
{
return Task.FromResult();
}, OnUserInformationReceived = (context) =>
{
return Task.FromResult();
},
OnRedirectToIdentityProvider = (context) =>
{
//设置重定向地址,解决生产环境nginx+https访问,还是有问题。。。。。。。
context.Properties.RedirectUri = $"{ClientUrl}/signin-oidc";
//context.ProtocolMessage.RedirectUri = $"{ClientUrl}/signin-oidc";
return Task.FromResult();
}, OnTokenValidated = (context) =>
{
//context.Properties.RedirectUri = $"{ClientUrl}/signin-oidc";
return Task.FromResult();
},
};
});
}

IdentityServer4-HybridAndClientCredentials的更多相关文章

  1. IdentityServer4 简单使用,包括api访问控制,openid的授权登录,js访问

    写在前面 先分享一首数摇:http://music.163.com/m/song?id=36089751&userid=52749763 其次是:对于identityServer理解并不是特别 ...

  2. IdentityServer4 实现 OpenID Connect 和 OAuth 2.0

    关于 OAuth 2.0 的相关内容,点击查看:ASP.NET WebApi OWIN 实现 OAuth 2.0 OpenID 是一个去中心化的网上身份认证系统.对于支持 OpenID 的网站,用户不 ...

  3. 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理(内容可能会有部分,推荐看源视频学习) 前言 由于之前的博客都是基于其他的博客进行开发,现在重新整理一下方便 ...

  4. 使用 IdentityServer4 实现 OAuth 2.0 与 OpenID Connect 服务

    IdentityServer4 是 ASP.NET Core 的一个包含 OIDC 和 OAuth 2.0 协议的框架.最近的关注点在 ABP 上,默认 ABP 也集成 IdentityServer4 ...

  5. IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity

    IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...

  6. IdentityServer4 中文文档 -13- (快速入门)切换到混合流并添加 API 访问

    IdentityServer4 中文文档 -13- (快速入门)切换到混合流并添加 API 访问 原文:http://docs.identityserver.io/en/release/quickst ...

  7. IdentityServer4【QuickStart】之使用asp.net core Identity

    使用asp.net core Identity IdentityServer灵活的设计中有一部分是可以将你的用户和他们的数据保存到数据库中的.如果你以一个新的用户数据库开始,那么,asp.net co ...

  8. webapi core2.1 IdentityServer4.EntityFramework Core进行配置和操作数据

    https://identityserver4.readthedocs.io/en/release/quickstarts/8_entity_framework.html 此连接的实践 vscode ...

  9. IdentityServer4 Hybrid 模式

    原文参考:Switching to Hybrid Flow and adding API Access back 接上篇:IdentityServer-Protecting an API using ...

  10. IdentityServer4中文文档

    欢迎IdentityServer4 IdentityServer4是ASP.NET Core 2的OpenID Connect和OAuth 2.0框架. 它在您的应用程序中启用以下功能: 认证即服务 ...

随机推荐

  1. autoware安装

    1.Autoware的地址为https://github.com/CPFL/Autoware2.Install dependencies for Ubuntu 16.04 kinetic安装教程ins ...

  2. 使用VirtualBox实现端口转发,以SSH与Django为例

    先来认识几个概念 (1)IP地址:又称为互联网协议地址,是计算机的物理地址,相当于计算机的编号,是32位的二进制数,通常被分割成4个8位的二进制数: (2)端口:指设备与外界通讯的接口,一台计算机的端 ...

  3. 【ABCD组】Scrum meeting 4

    前言 第4次会议在6月16日由组长在教9 405召开. 主要对下一步的工作进行说明安排,时长90min. 主要内容 分配下阶段任务,争取在这阶段完成软件的设计阶段 任务分配 姓名 当前阶段任务 贡献时 ...

  4. wcf--知识点

    WCF创建自托管服务 //自托管 WCF服务 //1.创建宿主 ServiceHost host = new ServiceHost(typeof(TaoBaoWCFServiceContract.T ...

  5. BZOJ 3037 创世纪 树形DP

    题目大意:给定一张有向图,每一个点有且仅有一条出边,要求若一个点x扔下去,至少存在一个保留的点y,y的出边指向x,求最多扔下去多少个点 首先原题的意思就是支配关系 我们反向考虑 求最少保留的点 要求一 ...

  6. 关于move_uploaded_file()出错的问题

    move_upload0ed_file()函数返回參数较少.可是引起出错的原因却有非常多,所以对于刚開始学习的人难免会遇到问题. 出错原因大概有下面三点: 1.假设检測到文件不是来自post上传.这个 ...

  7. laravel接口设计

    在各种公共方法都设计好,软件安装成功的条件下 routes/web.php中路由信息如下 <?php /* |------------------------------------------ ...

  8. Linux之convert命令【转】

    本文转载自:http://zlb1986.iteye.com/blog/778054 转载: 强大的convert命令 convert命令可以用来转换图像的格式,支持JPG, BMP, PCX, GI ...

  9. bzoj1833: [ZJOI2010]count 数字计数(数位DP+记忆化搜索)

    1833: [ZJOI2010]count 数字计数 题目:传送门 题解: 今天是躲不开各种恶心DP了??? %爆靖大佬啊!!! 据说是数位DP裸题...emmm学吧学吧 感觉记忆化搜索特别强: 定义 ...

  10. B1968 [Ahoi2005]COMMON 约数研究 数论

    大水题,一分钟就做完了...直接枚举1~n就行了,然后在n中判断出现多少次. 题干: Description Input 只有一行一个整数 N(0 < N < 1000000). Outp ...