【netcore基础】wwwroot下静态资源文件访问权限控制

本文参考如下博问

https://q.cnblogs.com/q/107836

 

业务要求

上传的资源文件(.mp3 .mp4等)只有购买了之后才能有权限访问,所以对上传的资源文件目录进行访问权限控制

地址举例

https://localhost:5001/assets/upload/images/20181018/0d9819d2-14d2-47eb-a763-be9d19c69e42.mp4

后面的文件目录是对应上 wwwroot 下,上传的资源目录,正常情况下所有用户都可以访问,这里我们要控制权限,只有购买订单的用户才能访问。

 

首先

在 Startup.cs 文件的 Configure 方法里配置如下代码

            app.UseWhen(
                c => c.Request.Path.Value.Contains("assets"),
                _ => _.UseMiddleware<AuthorizeStaticFilesMiddleware>());

            app.UseStaticFiles();

这里我们判断包含关键字的请求才会交给 AuthorizeStaticFilesMiddleware 中间件去处理。

AuthorizeStaticFilesMiddleware  代码

using GeduData.Server;
using GeduService.Interface;
using GeduService.Req;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace GeduDistributionApi.Extension
{
    public class AuthorizeStaticFilesMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IResourceService _resourceService;

        public AuthorizeStaticFilesMiddleware(
            RequestDelegate next

            , IResourceService resourceService
            )
        {
            _next = next;
            _resourceService = resourceService;
        }

        public async Task Invoke(HttpContext context, IAuthorizationService authorService)
        {
            var url = context.Request.GetAbsoluteUri();
            var sid = context.Request.Headers["sid"].ToString();
            if (string.IsNullOrEmpty(sid))
            {
                throw new GeduException("resource 403 forbidden sid is empty");
            }

            var result = _resourceService.ValidateResourceAuthor(new ValidateResourceAuthorReq
            {
                Url = url,
                SID = sid,
            });

            if (result.IsSucess == false)
            {
                await context.ForbidAsync();
            }

            await _next(context);
        }

    }
}

 

这里我们获取到请求头的 sid ,这个 sid 是我们自己定义的登录授权,可以理解为 token,里面附带了用户信息

下面就是业务逻辑处理的代码,供参考

 public ValidateResourceAuthorResp ValidateResourceAuthor(ValidateResourceAuthorReq req)
        {
            var loginUser = UserHelper._GetUser(req.SID);

            if (string.IsNullOrEmpty(req.Url))
            {
                throw new GeduException("url is empty");
            }
            //https://localhost:5001/assets/upload/images/20181018/0d9819d2-14d2-47eb-a763-be9d19c69e42.jpg
            req.Url = req.Url.Trim().ToLower();

            if (req.Url.EndsWith(".mp4") || req.Url.EndsWith(".mp3"))
            {
                //...
            }
            
            return new ValidateResourceAuthorResp
            {
                IsSucess = true,
            };
        }

 

这里就可以写自己的订单查询,资源权限的逻辑代码了,根据业务需求自定义

搞定

 

posted @ 2018-11-21 09:28  0539  阅读(4961)  评论(0编辑  收藏  举报