一、服务器

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中的replaceAll方法注意事项

    replaceAll和replace方法参数是不同的,replace的两个参数都是代表字符串,replaceAll的第一个参数是正则表达式 replaceAll中需要注意的特殊字符: \ == \\\ ...

  2. Git 基础教程 之 从远程库克隆

    ③  克隆一个本地仓库 a, 在合适的地方,在Git Bash下执行命令:         git clone git@github.com:hardy9sap/gittutorial.git

  3. Vue packages version mismatch

    开发过程中,之前做的vue项目,一段时间后拿出来重新运行,报错: 打开vue-template-compiler/index.js查看错误提示,如下: 当安装的vue版本和package.json中的 ...

  4. LightOJ - 1232 - Coin Change (II)

    先上题目: 1232 - Coin Change (II)   PDF (English) Statistics Forum Time Limit: 1 second(s) Memory Limit: ...

  5. Phone List POJ 3630 Trie Tree 字典树

    Phone List Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 29416   Accepted: 8774 Descr ...

  6. 6款程序猿不得不爱的bootstrap模板

    bootstrap模板是前端project师们的最爱!假设你还没有開始使用Bootstrap模板,那你可真是有够OUT,这是一个帮助你高速开发的工具.Bootstrap是基于jQuery框架开发的,它 ...

  7. dlopen failed: empty/missing DT_HASH in &quot;libx.so&quot; (built with --hash-style=gnu?)

    崩溃日志内容: java.lang.UnsatisfiedLinkError: dlopen failed: empty/missing DT_HASH in "libxxxx.so&quo ...

  8. hive正則表達式

    hive中实现正則表達式,与java中的正則表達式有所差别: 这里经过探索总结了一些: hive中的正则能够用,可是有所差别,差别在于原来的'\' 转义,这里变成了双斜杠了'\\' hive中的正则解 ...

  9. ASP怎样检測某目录是否存在,不存在则自己主动创建

    ASP怎样检測某目录是否存在,不存在则自己主动创建 folder=server.mappath("/imagess")  Set fso = CreateObject(" ...

  10. Nginx 源码安装和调优

    常见web架构: LAMP  =Linux+Apache+Mysql+PHP LNMP  =Linux+Nginx+Mysql+PHP   nginx概述: 知道:1  不知道:2 Nginx (&q ...