建立IdentityServer项目

官方学习文档:https://identityserver4.readthedocs.io/en/latest/intro/terminology.html

官方GitRepository:https://github.com/IdentityServer

1.下载IdentityServer4

根据官方文档描述:在CMD窗口执行这段代码即可

dotnet new -i IdentityServer4.Templates

 2.创建项目

项目模板名为is4inmem(即IdentityServer4 with In-Memory Strores and Test Users) 项目名称为IdentityProvide

我们打开对应文件目录发现已经为我们创建了这些文件夹。

 3.项目理解:

基于官方文档的图解:

 首先我们来观察两个类:

TestUser.cs对应Users

 Config.cs对应Client:

 4. Client Credentials

概念:The Client Credentials grant is used when applications request an access token to access their own resources, not on behalf of a user.

准备工作:

 创建一个控制台项目ConsoleClient需导入IdentityServer4库(去添加

 

 设置断点观察:

我们可以看到我们连接的Server路径和访问的Api。

 

 我们编写一个错误的TokenRequest设置错误的RequestSecret并不给予该用户访问Scope,这时候用户应该为非法的。

 现在我们修改成正确的形式:成功访问到Access Token

创建Api1Resource资源来供访问:

Add a new class called IdentityController:

using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Api1Resource.Controller
{
    [Route("identity")]
    [Authorize]
    public class IdentityController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(
                from c in  User.Claims select new {c.Type, c.Value});
        }
    }
}

配置StartUp.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace Api1Resource
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5001";

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

修改Console Client中的获取apiClient路径:

 先运行IdentityServer4服务端,在运行Api1Resource,最后运行Console Client 进行资源访问。

posted @ 2020-10-13 21:24  zhouslthere  阅读(115)  评论(0编辑  收藏  举报