一、服务器

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. Java基础之 HelloWorld

    1. Java发展史 参考: https://www.cnblogs.com/guoqingyan/p/5667064.html 2. Java中 JDK, JRE, JVM之间的关系 参考: htt ...

  2. C#--委托的同步,异步,回调函数

    原文地址 同步调用 委托的Invoke方法用来进行同步调用.同步调用也可以叫阻塞调用,它将阻塞当前线程,然后执行调用,调用完毕后再继续向下进行. using System; using System. ...

  3. Go语言net/http 解读.

    Http包提供实现HTTP客户端和服务端的方法与函数. Get.Head.Post.PostForm配合使用实现HTTP请求: resp, err := http.Get("http://e ...

  4. 笔记本联想(Lenovo)G40-70M加装内存和SSD固态硬盘

    笔记本联想(Lenovo)G40-70M加装内存和SSD固态硬盘 系列文章: 笔记本电脑提速之加装内存条.SSD固态硬盘.光驱位换SSD固态硬盘 笔记本ThinkPad E430c加装内存和SSD固态 ...

  5. 開始搭建第一个zookeeper

    首先须要下载zookeeper的tar包.地址为http://zookeeper.apache.org,然后再linux中解压并编译tar包. # tar-xvzf zookeeper-3.4.5.t ...

  6. 【cl】selenium实例2:打开百度,输入hello world

    /*创建的类为junit class*/ package Selenium_lassen; import static org.junit.Assert.*; import java.io.File; ...

  7. cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第0步---知识点总结&amp;效果预览&amp;设计思路

    /* 说明: **1.本次游戏实例是<cocos2d-x游戏开发之旅>上的最后一个游戏.这里用3.0重写并做下笔记 **2.我也问过木头本人啦,他说:随便写.第一别全然照搬代码:第二能够说 ...

  8. ubuntu下安装AndroidStudio

    近期将电脑的操作系统换成了ubuntu,对于不习惯win8/win10的人来说ubuntu确实是一个不错的选择,主要的软件都ok了,至于QQ什么的,大家能够去找wine版的,或者直接下载一个叫Cros ...

  9. RBF网络——核心思想:把向量从低维m映射到高维P,低维线性不可分的情况到高维就线性可分了

      RBF网络能够逼近任意的非线性函数,可以处理系统内的难以解析的规律性,具有良好的泛化能力,并有很快的学习收敛速度,已成功应用于非线性函数逼近.时间序列分析.数据分类.模式识别.信息处理.图像处理. ...

  10. [JavaEE] Apache Maven 入门篇(上)

    http://www.oracle.com/technetwork/cn/community/java/apache-maven-getting-started-1-406235-zhs.html 作 ...