Home > Backend Development > Golang > How to serve static files with route-based authorization using JWT in Gin?

How to serve static files with route-based authorization using JWT in Gin?

WBOY
Release: 2024-02-11 12:33:09
forward
1070 people have browsed it

go - 如何在 Gin 中使用 JWT 提供基于路由的授权的静态文件?

When it comes to writing web applications in Go, Gin is a very popular framework that provides a fast, flexible and easy-to-use way to build APIs and web applications. In many applications, we need to serve static files such as CSS, JavaScript, and images. At the same time, we also need a secure way to ensure that only authorized users can access these files. This article will introduce how to use JWT (JSON Web Token) in the Gin framework to implement route-based authorization and provide access to static files. If you want to learn how to implement this function in Gin, then follow php editor Xinyi to explore together!

Question content

I'm trying to serve a video from a directory. I know how to do it (r.Static("/videos", "./videos")) but I have a directory for each user like /videos/testuser/video .mp4. I have implemented a login system using JWT, but how can I only allow testuser to access /videos/testuser and user1 to access /videos/user1 ?

Thanks!

Workaround

Store the UserID in a JWT and parse the JWT claim when someone downloads the video. Depending on the user, use fmt.Sprintf("videos/%s/video.mp4", jwt.UserId) to get the required directory.

The above is the detailed content of How to serve static files with route-based authorization using JWT in Gin?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template