基于nginx实现视频播放流鉴权

1.前言:
基于 ZLMediaKit + wvp-GB28181-pro 搭建视频流媒体服务,引入摄像头,在业务项目中,嵌入实时监控播放和视频回放功能
ZLM返回的监控和视频回放流地址拿到即可播放/下载,基于安全考虑,需要对流地址添加鉴权

2.实现方案
通过nginx代理,转到业务项目,直接复用业务代码鉴权

2.1 nginx配置
修改nginx.conf配置,添加端口监听并重启nginx:

server {
    listen 1580;

    location /index/api/downloadFile {
     
        # 提取 GET 参数中的 authorization
        set $auth_token $arg_authorization;
        proxy_set_header Authorization $auth_token;

        # JWT 鉴权
        auth_request /auth;

	# 根据后端应用程序返回的响应来决定是否允许访问
        error_page  403              /403.html;
       
	# 执行请求
	proxy_pass http://127.0.0.1:1580/index/api/downloadFile;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

 	location = /403.html {
            return 403 ;
	}

    location = /auth {
        internal;
        proxy_pass http://127.0.0.1:2300/apiAccount/videoAuth;
        proxy_set_header X-Original-URI $request_uri;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Authorization $auth_token;
    }
  }

2.2 业务代码新增视频流鉴权接口

```
@Operation(summary = "视频回放鉴权")
@GetMapping(value = "/videoAuth", name = "视频回放鉴权")
boolean auth(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // 从header中获取token
    String token = request.getHeader(AccountConstant.AUTHORIZATION);
    if (StringUtils.isEmpty(token)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    // 替换%20
    token = token.replaceAll(AccountConstant.SPACE, " ");
    // 调用业务代码鉴权
    AuthEnum authEnum = authProvider.auth(token);
    if (AuthEnum.OK.equals(authEnum)) {
        return true;
    }
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    return false;
}
```

2.3 播放流带上业务token,实现播放鉴权
https://127.0.0.1:1580/index/api/downloadFile?file_path=/opt/media/bin/www/record/rtp/34020000001320000001_34020000001320000001/2024-10-24/09-29-59-0.mp4&Authorization=Bearer eyJhbGciOiJIUzU...

posted @ 2025-03-31 14:52  GT。  阅读(89)  评论(0)    收藏  举报