上节以对话形式,大概说了几种客户端授权模式的原理,这节重点介绍Hybrid模式在MVC下的使用。且为实现IdentityServer4从数据库获取User进行验证,并对Claim进行权限设置打下基础(第五节介绍)。
本节内容比较多,且涉及一、二节的内容,如有不懂,可先熟悉一、二节知识。
一、新建授权服务,命名为AuthServer新建Web API项目,不用配置HTTPS,不进行身份验证。
设置成控制台方式运行,端口设为5000。
安装IdentityServer4包
在Config.cs类中,添加如下代码:
public class Config { public static List<TestUser> GetUsers() { return new List<TestUser> { new TestUser { SubjectId = "1", Username = "test", Password = "123", Claims = new List<Claim> { new Claim("role", "user") } }, new TestUser { SubjectId = "2", Username = "admin", Password = "123", Claims = new List<Claim> { new Claim("role", "admin") } } }; } public static IEnumerable<IdentityResource> GetIdentityResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile(), //new IdentityResource("roles","role",new List<string>{ "role"}) }; } public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource("api1", "My API") //new ApiResource("api1", "My API",new List<string>(){ "role"}) }; } // clients want to access resources (aka scopes) public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { ClientId = "AuthServer", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { "api1" }, Claims= new List<Claim>(){new Claim("role","AuthServer") }, ClientClaimsPrefix = "" }, // OpenID Connect implicit flow client (MVC) new Client { ClientId = "mvc", ClientName = "MVC Client", AllowedGrantTypes = GrantTypes.Hybrid, ClientSecrets = { new Secret("secret".Sha256()) }, // where to redirect to after login RedirectUris = { ":5002/signin-oidc" }, // where to redirect to after logout PostLogoutRedirectUris = { ":5002/signout-callback-oidc" }, AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, //"roles" } } }; } }