ASP.NET Core IdentityServer4 新手上路

OAuth2.0资料

今天看到一篇博主写了该系列文章,贴图和过程都比较详细,俗话说实践是检验真理的惟一标准(若是是按照参考文章复制粘贴,应该不会出现踩坑,可是我喜欢本身手动敲一遍),发现几个坑,于是总结下经验,让其余小白同窗少走弯路html

参考第一篇:http://www.javashuo.com/article/p-cdzjgnix-hm.htmlgit

参考第二篇:http://www.javashuo.com/article/p-mtkmsggb-gs.htmlweb

博客园晓晨的关于identityServer4的中文文档地址: http://www.cnblogs.com/stulzq/p/8119928.htmldocker

Docker中文文档 https://yeasy.gitbooks.io/docker_practice/content/api

OAuth2.0(Open Authorization)是一个开放受权协议;第三方应用不须要接触到用户的帐户信息(如用户名密码),经过用户的受权访问用户资源服务器

OAuth的步骤通常以下:restful

一、客户端要求用户给予受权
二、用户赞成给予受权
三、根据上一步得到的受权,向认证服务器请求令牌(token)
四、认证服务器对受权进行认证,确认无误后发放令牌
五、客户端使用令牌向资源服务器请求资源
六、资源服务器使用令牌向认证服务器确认令牌的正确性,确认无误后提供资源app

服务端代码实现

第一步:新建一个webapi空项目

第二步:添加Nuget包:IdentityServer4

第三步:新建一个帮助类(类名自定义便可),用来建立IdentityServer4.Model生成受权token

    public class Config
    {

        /// <summary>
        /// 全部能够访问的Resource
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource>
            {
          //第一个参数须要与下面标记红色字体保持一致,能够随意命名,可是请注意大小写,第二个参数 我干了,你随意。
new ApiResource("api","My Api") }; } /// <summary> /// 客户端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client() { ClientId="client", ////模式:最简单的模式 AllowedGrantTypes=GrantTypes.ClientCredentials, ClientSecrets= { new Secret("secret".Sha256()) }, AllowedScopes={ "api"} } }; } }

第一处坑讲解:上面代码红色标记,请注意大小写,若是一个大写,一个小写。当你受权的时候会提示错误ide

1

第四步:修改Startup.cs  红色字体是须要加的方法和中间件

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

           
 services.AddIdentityServer() .AddDeveloperSigningCredential()//添加开发人员签名凭据
            .AddInMemoryApiResources(Config.GetResources())//添加内存apiresource
            .AddInMemoryClients(Config.GetClients());//添加内存client

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseIdentityServer();//使用IdentityServer
            app.UseMvc();

        }
    }

第五步:修改Program.cs  其实这一步能够省略掉,由于这一部将api不托管在IIS Express上,经过控制台程序启动。  自定义路径配置以下

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }



        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
          //该处端口能够自定义 只要不与你其余端口冲突就好 .UseUrls(
"http://localhost:5000"); }

第二处坑讲解:生成token的服务端已经所有设置完成,若是你按照之前习惯,启动F5---会发现自定义端口未起做用。你须要设置一下才行post

3

http://localhost:5000/.well-known/openid-configuration访问 ;能够看到是一个restful的api

4

 而后用postman神器 服务端成功,我们开始用客户端

5

客户端代码实现

第一步:新建一个webapi空项目  

第二步:添加Nuget包:IdentityServer4.AccessTokenValidation

第三步:修改Startup.cs  红色字体是须要加的方法和中间件

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

 services.AddAuthentication("Bearer")//添加受权模式
            .AddIdentityServerAuthentication(Options =>
            {
                Options.Authority = "http://localhost:5000";//受权服务器地址
                Options.RequireHttpsMetadata = false;//是不是https
                Options.ApiName = "api"; });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();//使用受权中间件

            app.UseMvc();
        }
    }

第三处坑讲解:

1.受权服务地址端口号,请按照服务端配置的端口号来,若是用IIS Express,请右键项目属性->调试查看。

2.Options.ApiName = "api";   请看上述踩坑一配置的名称,大小写须要统一

第四步:修改Program.cs  其实这一步能够省略掉,由于这一部将api不托管在IIS Express上,经过控制台程序启动。与上述服务端配置同样。记得将端口号修改

第四处须要注意的地方

须要将服务端运行起来,而后再运行客户端(顺序不重要,重要的是必须两个程序都启动起来。能够将服务端发布到IIS上,客户端经过vs运行。我比较懒,分别打开两个,一个设置为启动服务端,一个设置为启动客户端)

第五步:添加受权标签   能够在action和controller上添加

        [HttpGet]
        [Authorize] 
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

添加在action上,表示这个方法须要受权才能访问,不然访问不了

添加在controller上,表示整个controller下的全部action方法都须要受权后才能访问   

下图是成功,若是空白表示受权失败(你能够打个断点)。 

出现一些错误码html(<title>Internal Server Error</title>)在里面,是由于服务端没启动成功

6

须要注意的地方:受权码  前面必须加Bearer 而后空格

在客户端配置第三步中 services.AddAuthentication("Bearer")//添加受权模式  有的同窗可能会想  那我将这个改掉  而后保持一致应该能够

恭喜这位同窗想法很是棒,可是你能够试一试。这个格式是固定规范

相关文章
相关标签/搜索