用户基于角色授权

1 用户基于角色授权

1.1  在 id4 server 上新增用户 user1 和 user2 ,然后在user1和user2 添加 role 声明,user1(角色声明值为 user1_role),user2(角色声明值为 user2_role)

 

 

 

 1.2 在 id4 server中 添加 身份资源(identity resource)名为 roles 并在roles身份资源上添加 role 声明

添加 名为 roles 的身份资源如下图

 

 

 

 1.3 在 client 中设置 client 允许的 scope 添加 1.2 加的 roles身份资源 并设置允许授权类型为 hybrid 然后勾选设置client 始终在身份令牌中包含用户声明

 

 1.4 在 client 中修改 client 的Starup.cs代码如下,添加 请求 roles 的scope作用域,以及配置无权访问页面

using IdentityModel;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;

namespace MvcClient
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) // 生产环境请删除 appsettings.Development.json 文件,因为 appsettings.Development.json 文件在 appsettings.json 后面注册,会覆盖掉 appsettings.json 的相同配置
                .AddEnvironmentVariables();

            Configuration = configBuilder.Build();
        }

        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.AddRazorPages()
                .AddRazorRuntimeCompilation();

            services.AddControllersWithViews();

            #region 使用 oidc 认证
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // 包 System.IdentityModel.Tokens.Jwt;
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.AccessDeniedPath = "/Login/AccessDenied"; // 设置无权访问回调地址
                options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            })
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => // 安装包 Microsoft.AspNetCore.Authentication.OpenIdConnect
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                options.Authority = Configuration["AuthServer:Authority"]; // identity server 服务器地址
                options.ClientId = Configuration["AuthServer:ClientId"];
                options.ClientSecret = Configuration["AuthServer:ClientSecret"];
                //options.ResponseType = "code"; // 对应授权类型 authorization_code
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken; // 对应授权类型 hybrid
                options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["AuthServer:RequireHttpsMetadata"]);
                options.SaveTokens = true; // 把获取到的token写入到cookie
                //options.GetClaimsFromUserInfoEndpoint = true; // 拿到id_token之后自动向userinfo endpoint请求用户信息并放到asp.net core的User Identity下

                options.Scope.Clear();
                options.Scope.Add(OidcConstants.StandardScopes.OpenId);
                options.Scope.Add(OidcConstants.StandardScopes.Profile);
                options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);
                options.Scope.Add("roles"); // 请求 roles 作用域

                // 让Claim里面的角色成为mvc系统识别的角色
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role
                };
            });
            #endregion
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseRouting();

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

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

 

1.5  应用角色权限

 

 

 1.6 测试

用户 user1 登录系统成功后读取的 claims如下

 

 

 读取声明代码如下:

<p>用户声明:</p>
@foreach (var claim in User.Claims)
{
    <dt>@claim.Type</dt>
    <dd>@claim.Value</dd>
}

用户 user1 访问  User1RoleView 如下:

 

 

 但是 user1 无法访问 User2RoleView

 

 

 使用 user2 就可以访问 User2RoleView

 

 

 

 

参考链接

https://www.cnblogs.com/jesse2013/p/oidc-in-aspnetcore-with-identity-server.html

 

posted @ 2022-04-10 22:50  温故纳新  阅读(123)  评论(0编辑  收藏  举报