IdentityServer4

Memory

准备

  1. 安装IdentityServer
  2. 编写config类
using IdentityServer4.Models;
using System.Collections.Generic;

namespace Memory.Web.Core
{
    public static class Config
    {
        public static IEnumerable<ApiScope> ApiScopes => new[]
        {
            new ApiScope()
            {
                Name="sample_api",
                DisplayName="sample api"
            }
        };
        public static IEnumerable<Client> Clients => new[]
        {
            new Client()
            {
                ClientId="sample_client",
                ClientSecrets=new[]
                {
                    new Secret("sample_client_secret".Sha256())
                   
                },
                AllowedGrantTypes=GrantTypes.ClientCredentials,
                AllowedScopes=new []{ "sample_api" }
            }
        };
    }
}

  1. 在startup里配置identityserver
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConsoleFormatter();
        services.AddControllers().AddInjectWithUnifyResult();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        #region id4
        var builder = services.AddIdentityServer();
        builder.AddDeveloperSigningCredential();
        builder.AddInMemoryApiScopes(Config.ApiScopes);
        builder.AddInMemoryClients(Config.Clients);
        #endregion
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseInject();

        #region id4
        app.UseIdentityServer();
        #endregion
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
  1. 获取token
    在这里插入图片描述
  2. 编写测试api
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Memory.Web.Entry.Apis
{

    public class IdentityController : IDynamicApiController
    {
        [Authorize]
        public IActionResult Get()
        {            
            var c = (from claim in Furion.App.User.Claims select new { claim.Type, claim.Value }).ToList();
            return new JsonResult(c);
        }
    }
}
  1. 再startup中启用认证服务
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConsoleFormatter();
        services.AddControllers().AddInjectWithUnifyResult();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        #region id4
        var builder = services.AddIdentityServer();
        builder.AddDeveloperSigningCredential();
        builder.AddInMemoryApiScopes(Config.ApiScopes);
        builder.AddInMemoryClients(Config.Clients);
        #endregion
        #region 认证
        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", option =>
            {
                option.Authority = "https://localhost:5001";
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false

                };
            });
        #endregion
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseInject();

        #region id4
        app.UseIdentityServer();
        #endregion
        #region authority
        app.UseAuthentication();
        app.UseAuthorization();
        #endregion
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
  1. 将获取的token带入请求头
    在这里插入图片描述
  2. 启用授权
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConsoleFormatter();
        services.AddControllers().AddInjectWithUnifyResult();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        #region id4
        var builder = services.AddIdentityServer();
        builder.AddDeveloperSigningCredential();
        builder.AddInMemoryApiScopes(Config.ApiScopes);
        builder.AddInMemoryClients(Config.Clients);
        #endregion
        #region 认证
        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", option =>
            {
                option.Authority = "https://localhost:5001";
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false

                };
            });
        #endregion
        #region 授权
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiScope",//策略名
                builder =>
            {
                builder.RequireAuthenticatedUser();//通过认证的用户
                builder.RequireClaim("scope", "sample_api");//对claim的要求
            });
        });
        #endregion
    }
namespace Memory.Web.Entry.Apis
{
    [Authorize("ApiScope")]//策略名
    public class IdentityController : IDynamicApiController
    {
        public IActionResult Get()
        {            
            var c = (from claim in Furion.App.User.Claims select new { claim.Type, claim.Value }).ToList();
            return new JsonResult(c);
        }
    }
}

用户密码登录

  1. 再config.cs里新建用户
        public static List<TestUser> Users => new()
        {
            new TestUser()
            {
                SubjectId="1",
                Username="admin",
                Password="123"
            }
        };
  1. 增加密码验证client
            new Client
            {
                ClientId="sample_pass_client",
                ClientSecrets = new[]
                {
                    new Secret("sample_pass_client_secret".Sha256()),
                },
                AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
                AllowedScopes=new []{"sample_api"}
            }
  1. 再startup里,将用户添加到系统内
        var builder = services.AddIdentityServer();
        builder.AddDeveloperSigningCredential();
        builder.AddInMemoryApiScopes(Config.ApiScopes);
        builder.AddInMemoryClients(Config.Clients);
        builder.AddTestUsers(Config.Users);
  1. postman用密码登录获取token
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值