\n 使用NuGet安装Identity Server4 \n
\n\n
\n \n
\n 创建配置 \n
\n\n
\n
public class Config\n {\n public static IEnumerable<IdentityResource> GetIdentityResources()\n {\n return new IdentityResource[]\n {\n new IdentityResources.OpenId(),\n new IdentityResources.Profile()\n };\n }\n\n public static IEnumerable<ApiResource> GetApis()\n {\n return new List<ApiResource>\n {\n new ApiResource(\"api\", \"My API\")\n };\n }\n public static IEnumerable<Client> GetClients()\n {\n return new List<Client>\n {\n new Client\n {\n ClientId = \"client\",\n\n // no interactive user, use the clientid/secret for authentication\n AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,\n\n // secret for authentication\n ClientSecrets =\n {\n new Secret(\"secret\".Sha256())\n },\n AccessTokenLifetime = 1800,//设置AccessToken过期时间\n AbsoluteRefreshTokenLifetime = 2592000,//RefreshToken的最长生命周期,默认30天\n RefreshTokenExpiration = TokenExpiration.Sliding,//刷新令牌时,将刷新RefreshToken的生命周期。RefreshToken的总生命周期不会超过AbsoluteRefreshTokenLifetime。\n AllowOfflineAccess=true,//如果要获取refresh_tokens ,必须把AllowOfflineAccess设置为true\n // scopes that client has access to\n AllowedScopes =\n {\n \"api\",\n OidcConstants.StandardScopes.OfflineAccess,\n // OidcConstants.StandardScopes.OpenId,//如果要获取id_token,必须在scopes中加上OpenId和Profile,id_token需要通过refresh_tokens获取AccessToken的时候才能拿到(还未找到原因)\n //OidcConstants.StandardScopes.Profile//如果要获取id_token,必须在scopes中加上OpenId和Profile\n }\n }\n };\n }\n
\n 实现IResourceOwnerPasswordValidator接口,自定义用户登录 \n
\n\n
\n
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator\n {\n public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)\n {\n //此处可以通过数据库获取用户登录验证\n if (context.UserName == \"admin\" && context.Password == \"123\")\n {\n context.Result = new GrantValidationResult(subject: \"admin\", authenticationMethod: \"custom\");\n }\n else\n {\n context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, \"invalid custom credential\");\n }\n return Task.FromResult(0);\n }\n }\n
\n
\n
\n 在Startup增加服务 \n
\npublic void ConfigureServices(IServiceCollection services)\n {\n services.AddIdentityServer()\n .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())\n .AddInMemoryIdentityResources(Config.GetIdentityResources())\n .AddInMemoryApiResources(Config.GetApis())\n .AddInMemoryClients(Config.GetClients())\n .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();//注入自定义用户登录验证;\n\n //注入基本的MVC服务\n services.AddMvcCore()\n //注入MVC的认证服务,对应控制器的Authorize特性\n .AddAuthorization()\n //注入MVC格式化程序,对应JsonResult等等的格式化操作,主要用于控制器返回值的格式化操作\n .AddJsonFormatters();\n\n //注入身份认证服务,设置Bearer为默认方案\n services.AddAuthentication(\"Bearer\")\n //注入并配置Bearer为默认方案的基本参数\n .AddIdentityServerAuthentication(options =>\n {\n //设置令牌的发布者\n options.Authority = \"http://localhost:59090\";\n //设置Https\n options.RequireHttpsMetadata = false;\n //需要认证的api资源名称\n options.ApiName = \"api\";\n });\n\n services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);\n }\n
public void Configure(IApplicationBuilder app, IHostingEnvironment env)\n {\n if (env.IsDevelopment())\n {\n app.UseDeveloperExceptionPage();\n }\n else\n {\n // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n app.UseHsts();\n }\n\n app.UseIdentityServer();\n app.UseHttpsRedirection();\n app.UseMvc();\n }\n
\n 使用Postman调用登录获取token \n
\n\n
\n \n
\n 刷新token \n
\n\n
\n \n
\n 在需要授权的接口需要加上[Authorize]特性 \n