zoukankan      html  css  js  c++  java
  • 最简单的IdentityServer实现——Api

    1.创建项目并添加引用

    创建ASP.NET Core Web API项目IdentityServer.EasyDemo.Api

     
    1
     
    2


    引用IdentityServer4.AccessTokenValidation

     
    3

    2.定义一个Api接口

    新增接口文件IdentityController.cs,用于测试授权
    如果你直接访问http://localhost:5001/identity ,你会得到一个401错误,因为调用这个接口需要凭证
    这里设置一个Api接口,路由是"identity",跟传统的/controller/action访问路由不同,GET请求访问/identity即可

    [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 });
        }
    }
    

    3.配置Api

    services添加IdentityServerAuthentication,设置授权地址为IdentityServer的网址(这里保证了在用户访问到未授权的方法时,会自动跳转到IdentityServer的授权页面)
    注意保证Api的ApiName在IdentityServer的Api集合中

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                //将认证服务添加到DI,配置"Bearer"作为默认方案
                .AddAuthorization()
                .AddJsonFormatters();
    
            services.AddAuthentication("Bearer")
                //将IdentityServer访问令牌验证处理程序添加到DI中以供身份验证服务使用
                .AddIdentityServerAuthentication(options =>
                {
                    //用于授权的地址
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    //该Api项目对应的IdentityServer的Api资源,与GetApiResources方法里面的Api名称对应
                    options.ApiName = "api1";
                });
        }
    
        public void Configure(IApplicationBuilder app)
        {
            //将认证中间件添加到流水线中,以便在对主机的每次呼叫时自动执行认证
            app.UseAuthentication();
    
            app.UseMvc();
        }
    }
    

    4.在属性中将Api项目的端口号设置为5001

     
    4
  • 相关阅读:
    后端注册接口完善
    编写注册接口
    Git 多人开发及常见问题
    Git 常用命令
    GIT 的安装及配置SSH
    ORM查询方法(整理)
    HTTP的系列理解与整理
    Unity C# 反射
    C# 中的委托和事件
    Unity C# 运用 GetSaveFileName() 导出Excel文件
  • 原文地址:https://www.cnblogs.com/Lulus/p/7986623.html
Copyright © 2011-2022 走看看