zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
using Bootstrap.Security.Authentication;
using Bootstrap.Security.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
 
namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// BootstrapAdminAuthorization 认证服务扩展类
    /// </summary>
    public static class AuthenticationExtensions
    {
#nullable disable
        private static Func<string, string, IEnumerable<string>> _urlAuthHandler;
        private static Func<string, IEnumerable<string>> _appAuthHandler;
        private static Func<string, IEnumerable<string>> _userAuthHandler;
#nullable restore
 
        /// <summary>
        /// 添加 BootstrapAdmin 认证授权服务,内部调用 UseAuthentication
        /// </summary>
        /// <param name="builder">IApplicationBuilder 实例</param>
        /// <param name="userNameAuthHandler">通过用户名称获得角色集合代理方法</param>
        /// <param name="urlAuthHandler">通过请求地址获得角色集合代理方法</param>
        /// <param name="appAuthHandler">通过用户名称获得应用程序集合代理方法</param>
        public static IApplicationBuilder UseBootstrapAdminAuthentication(this IApplicationBuilder builder, Func<string, IEnumerable<string>> userNameAuthHandler, Func<string, string, IEnumerable<string>> urlAuthHandler, Func<string, IEnumerable<string>> appAuthHandler)
        {
            builder.UseAuthentication();
 
            // 增加模拟用户中间件
            builder.Use(async (context, next) =>
            {
                BootstrapAppContext.SetProvider(context.RequestServices);
                var userName = context.RequestServices.GetRequiredService<IConfiguration>().GetValue("SimulateUserName", "");
                if (!string.IsNullOrEmpty(userName))
                {
                    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                    context.User = new ClaimsPrincipal(identity);
                }
 
                // 检查用户登录名
                if (context.User.Identity.IsAuthenticated && (string.IsNullOrEmpty(context.User.Identity.Name) || !userNameAuthHandler(context.User.Identity.Name).Any()))
                {
                    await context.SignOutAsync();
                    await context.ChallengeAsync();
                    return;
                }
 
                if (context.User.Identity.IsAuthenticated && !string.IsNullOrEmpty(context.User.Identity.Name))
                {
                    AddRoles(context.User, RetrieveRolesByUserName(context.User.Identity.Name), new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
                }
                await next();
            });
 
            // Web api Validate
            builder.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), app => app.Use(async (context, next) =>
            {
                if (!context.User.Identity.IsAuthenticated)
                {
                    JwtAuthentication(context);
                }
 
                if (context.User.Identity.IsAuthenticated && !string.IsNullOrEmpty(context.User.Identity.Name))
                {
                    AddRoles(context.User, RetrieveRolesByUserName(context.User.Identity.Name), new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme));
                }
                await next();
            }));
 
            _urlAuthHandler = urlAuthHandler;
            _appAuthHandler = appAuthHandler;
            _userAuthHandler = userNameAuthHandler;
            return builder;
        }
 
        /// <summary>
        /// 通过指定用户名获取授权角色集合
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        internal static IEnumerable<string> RetrieveRolesByUserName(string userName) => _userAuthHandler(userName);
 
        /// <summary>
        /// 通过指定访问地址获取授权角色集合
        /// </summary>
        /// <param name="url">指定地址</param>
        /// <param name="appId">应用程序ID</param>
        /// <returns>角色集合</returns>
        internal static IEnumerable<string> RetrieveRolesByUrl(string url, string appId) => _urlAuthHandler(url, appId);
 
        /// <summary>
        /// 通过指定用户名获取授权 App 集合
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>应用程序集合</returns>
        internal static IEnumerable<string> RetrieveAppsByUserName(string userName) => _appAuthHandler(userName);
 
        /// <summary>
        /// 添加 Claim 到当前用户实例中
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roles"></param>
        /// <param name="identity"></param>
        internal static void AddRoles(ClaimsPrincipal user, IEnumerable<string> roles, ClaimsIdentity identity)
        {
            roles?.ToList().ForEach(role => identity.AddClaim(new Claim(ClaimTypes.Role, role)));
            user.AddIdentity(identity);
        }
 
        private static void JwtAuthentication(HttpContext context)
        {
            // Jwtbeare authorization
            var token = context.Request.Headers["Authorization"].LastOrDefault();
            if (!string.IsNullOrEmpty(token) && token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                token = token.Substring(7);
 
                // validate token
                var tokenOption = context.RequestServices.GetRequiredService<IConfiguration>().GetOption(() => new TokenValidateOption());
                var tokenHandler = new JwtSecurityTokenHandler();
                context.User = tokenHandler.ValidateToken(token, new TokenValidationParameters()
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOption.SecurityKey)),
                    ValidIssuer = tokenOption.Issuer,
                    ValidAudience = tokenOption.Audience
                }, out var securityToken);
            }
        }
    }
}