配套源码:https://gitee.com/jardeng/IdentitySolution
本篇将创建使用[Code-授权码]授权模式的客户端,来对受保护的API资源进行访问。
1、接上一篇项目,因为之前创建IdentityServer认证服务器没有使用IdentityServer4提供的模板,在Code授权码模式就没有进行登录、授权的界面,所以重新创建一下IdentityServer项目。
重新使用IdentityServer4模板 - is4inmem创建项目。
将之前IdentityServer认证服务器Config.cs复制到新建的IdentityServer服务器即可,最后的IdentityServer认证服务器项目结构为:
然后在IdentityServer项目Config.cs中添加一个返回身份资源的方法
然后在IdentityServer项目Config.cs中添加一个客户端
注意:localhost:6001指的是我们将要创建的MVC客户端的项目地址,并非IdentityServer认证服务器的地址
/// 授权码模式(Code) /// 适用于保密客户端(Confidential Client),比如ASP.NET MVC等服务器端渲染的Web应用 new Client { ClientId = "mvc client", ClientName = "ASP.NET Core MVC Client", AllowedGrantTypes = GrantTypes.Code, ClientSecrets = { new Secret("mvc secret".Sha256()) }, RedirectUris = { "http://localhost:6001/signin-oidc" }, FrontChannelLogoutUri = "http://localhost:6001/signout-oidc", PostLogoutRedirectUris = { "http://localhost:6001/signout-callback-oidc" }, AlwaysIncludeUserClaimsInIdToken = true, AllowOfflineAccess = true, AllowedScopes = { "api1", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, IdentityServerConstants.StandardScopes.Address, IdentityServerConstants.StandardScopes.Phone } }