.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

原文: .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

1、客户端模式介绍

客户端模式(Client Credentials Grant)是指客户端直接向认证服务(Authorization Server)发送认证请求,获取token,进行认证,通常适用于受信任的客户端。
java

image.png

请求步骤为:

  • 客户端向认证服务器进行认证,并请求一个访问令牌token
  • 认证服务器进行认证,经过以后,返回客户端一个访问令牌。

2、建立认证服务

  • 建立一个认证服务IdentityServerCenter,经过NuGet安装IdentityServer4
  • 添加配置资源与客户端的文件,引入using IdentityServer4.Models
public class Config {
        public static IEnumerable<ApiResource> GetResources() {
            return new List<ApiResource> {
                    new ApiResource {
                        Name = "ImageResource",
                        Scopes={ new Scope ("ImageResource")},//Scopes必须配置,不然获取token时返回 invalid_scope
                    },
                    new ApiResource { Name = "FileResourse" },
                    new ApiResource { Name="Api",    Scopes={new Scope ("Api") } }
                };
        }
        public static IEnumerable<Client> GetClients() {
            return new List<Client> {
                    new Client {
                        ClientId = "ClientId",
                        AllowedGrantTypes =GrantTypes.ClientCredentials,//受权模式:客户端模式
                        AllowedScopes={ "ImageResource","Api" }, //容许访问的资源 GetResources()中配置的
                       ClientSecrets={ new Secret { Value= "ClientSecret".Sha256(), Expiration=DateTime.Now.AddMinutes(5)} }
                    } };
        }
    }
  • 注入IdentityServer4,添加IdentityServer4配置
public void ConfigureServices(IServiceCollection services) {
            //注入IdentityServer 添加IdentityServer4配置
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetResources()) //添加配置的资源ApiResource
                .AddInMemoryClients(Config.GetClients());//添加配置的客户端Client
          // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
  • 使用IdentityServer4
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            //使用IdentityServer
            app.UseIdentityServer();
        }
  • 启动项
    image.png

    因为未使用MVC,访问该api返回404。IdentityServer4提供一个地址可获取相关配置项。
http://examplehostname.com.well-known/openid-configuration/

访问 http://localhost:5000/.well-known/openid-configuration 将返回的信息序列化以下
api

image.png

scopes_supported": ["ImageResource", "Api", "offline_access"]即为 Config中配置的访问的资源 AllowedScopes

  • 使用postman获取token
    image.png

    grant_type为客户端受权client_credentials,client_idClient_SecretConfig中配置的ClientIdSecret。接下来建立一个可访问的资源。

3、建立资源服务

  • 建立一个资源服务项目ImageResourceApi
  • 注入认证
public void ConfigureServices(IServiceCollection services) {
            services.AddAuthentication(config => {
                config.DefaultScheme = "Bearer"; 
            }).AddIdentityServerAuthentication(option=> {
                option.ApiName = "ImageResource"; 
                option.Authority = "http://localhost:5000"; //认证服务的url
                option.ApiSecret = "ClientSecret".ToSha256();// 访问的secret
                option.RequireHttpsMetadata = false;
                
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
      public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            //使用认证
            app.UseAuthentication();
            app.UseMvc();
        }
  • 启动资源服务,返回401未受权;
  • 使用postman带着token请求资源服务ImageResourceApi,请求成功。
    image.png
相关文章
相关标签/搜索