一、服务器

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. mongodb集群搭建(分片+副本)

    原文地址:https://www.cnblogs.com/ityouknow/p/7344005.html 相关概念 先来看一张图: 从图中可以看到有四个组件:mongos.config server ...

  2. 阿里云对象存储服务,OSS使用经验总结,图片存储,分页查询

    阿里云OSS-使用经验总结,存储,账号-权限,分页,缩略图,账号切换 最近项目中,需要使用云存储,最后选择了阿里云-对象存储服务OSS.总的来说,比较简单,但是仍然遇到了几个问题,需要总结下. 1.O ...

  3. 多层下firebird自增长字段的处理

    使用unidac可以解决自增长字段处理的问题. 对于多层就是一个比较烦人的事情,解决办法:cliendataset中自增长字段的处理:id:自增长字段.在client中的处理方法:clientdata ...

  4. Java Web学习总结(19)——web.xml配置详解

    1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Servl ...

  5. mongodb drop不释放磁盘空间

    点击(此处)折叠或打开 use demodb //使用demodb,以下假设操作的collection是foo db.foo.remove({"id":"123456&q ...

  6. 0804SHOW ENGINE INNODB STATUS

    转自http://blog.csdn.net/github_26672553/article/details/52931263 innodb存储引擎在show engine innodb status ...

  7. 0214常用的SQL语句

    1MYSQL自己认为 \n 就是 换行. 如果想表达 \n 则用户必须以 \\n的方式来说明 SELECT CONCAT('"C:\\Program Files\\MySQL\\MySQL ...

  8. 今天玩了tensorflow playground,太好玩了

    先上地址: http://playground.tensorflow.org 我试了一个最复杂的,螺旋形的.开始怎么训练都不行.后来我多加了几个神经元,居然能训练成功了.真是太牛逼了!

  9. Objective-C学习笔记(二十二)——初始化方法init的重写与自己定义

    初学OC.对init这种方法不是非常了解.我们如今来分别对init方法进行重写以及自己定义,来加深对他的了解. 本样例也是用Person类来进行測试. (一)重写init方法. (1)在Person. ...

  10. Python 远程调用MetaSploit

    (1)安装Python的msgpack类库.MSF官方文档中的数据序列化标准就是參照msgpack. root@kali:~# apt-get install python-setuptools ro ...