.Netcore 默认认证授权

新建Webapi 项目

Startup.cs 有

app.AddAuthentication();

这是个中间件,

public async Task Invoke(HttpContext context)
        {
            context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
            {
                OriginalPath = context.Request.Path,
                OriginalPathBase = context.Request.PathBase
            });
 
            // Give any IAuthenticationRequestHandler schemes a chance to handle the request
            var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
                if (handler != null && await handler.HandleRequestAsync())
                {
                    return;
                }
            }
 
            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
            if (defaultAuthenticate != null)
            {
                var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
                if (result?.Principal != null)
                {
                    context.User = result.Principal;
                }
            }
 
            await _next(context);
        }

  这里有 给context.User 赋值的,实际上就是HttpContext 。

HttpContext 在Controller的基类里有直接访问的。就是这里的赋值在后面的Controller 的HttpContext 可以读取。ControllerBase里也有User 属性: User=>HttpContext?.User

可以建一个父类,封装下,直接读取UserName 和 Role

    [Route("api/[controller]")]
    [ApiController]
    public class BaseController : ControllerBase
    {
       
        protected string UserName
        {
            get
            {
               
                return User.Identity.Name;
            }
        }



        protected Role Role
        {
            get
            {
                var s = User.Claims.FirstOrDefault(t => t.Type.EndsWith("role"))?.Value;
                if (!string.IsNullOrWhiteSpace(s))
                {
                    return (Role)Enum.Parse(typeof(Role), s);
                }
                return Role.Invaild;
            }

        }

        protected Role[] Roles
        {
            get
            {
                return User.Claims.Where(t => t.Type.EndsWith("role"))?.Select(t=> (Role)Enum.Parse(typeof(Role), t.Value)).ToArray();
                //if (!string.IsNullOrWhiteSpace(s))
                //{
                //    return (Role)Enum.Parse(typeof(Role), s);
                //}
                //return Role.Invaild;
            }
        }
    }

  

.Netcore 默认认证授权

上一篇:ASP.NET Core 3.1 微软官方教程


下一篇:Akamai 网络报告出炉,物联网安全令人担忧