【netcore基礎】wwwroot下靜態資源文件訪問權限控制

本文參考以下博問app

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

 

業務要求url

上傳的資源文件(.mp3 .mp4等)只有購買了以後纔能有權限訪問,因此對上傳的資源文件目錄進行訪問權限控制spa

地址舉例code

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

後面的文件目錄是對應上 wwwroot 下,上傳的資源目錄,正常狀況下全部用戶均可以訪問,這裏咱們要控制權限,只有購買訂單的用戶才能訪問。blog

 

首先token

在 Startup.cs 文件的 Configure 方法裏配置以下代碼資源

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

            app.UseStaticFiles();

這裏咱們判斷包含關鍵字的請求才會交給 AuthorizeStaticFilesMiddleware 中間件去處理。get

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,
            };
        }

 

這裏就能夠寫本身的訂單查詢,資源權限的邏輯代碼了,根據業務需求自定義

搞定

相關文章
相關標籤/搜索