<abbr id="pe8jl"><table id="pe8jl"></table></abbr>

    1. <bdo id="pe8jl"></bdo>
    2. <pre id="pe8jl"><fieldset id="pe8jl"></fieldset></pre>
      1. \n
        \n\n\n\n

        The index.html is a simple web page that provides a user interface for displaying the login status of a user. It uses Bootstrap for styling and Font Awesome for icons. On page load, it checks the user's authentication status by sending a request to the server with a JWT token stored in localStorage. If the user is logged in, it shows a success message with the user's name and a logout button. If not logged in, it shows a message indicating the user is not logged in and redirects them to the login page after a few seconds.<\/p>\n\n

        \n \n \n login.html\n<\/h3>\n\n\n\n
        \n\n\n    \n    \n    \n    \n<\/head>\n
        

        亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

        \n
        \n\n\n\n

        The login.html page provides a simple login form where users can input their username and password. It uses Bootstrap for styling and Font Awesome for icons. When the user submits the form, a JavaScript function login() sends a POST request to the \/login endpoint with the entered credentials. If the login is successful, the server returns a JWT token, which is stored in localStorage. The page then redirects the user to the home page (\/). If the login fails, an error message is displayed.<\/p>\n\n

        \n \n \n Run project\n<\/h2>\n\n\n\n
        go run main.go\n<\/pre>\n\n\n\n

        打開網(wǎng)絡(luò)瀏覽器并轉(zhuǎn)到http:\/\/localhost:8080

        \n你會發(fā)現(xiàn)這個測試頁。<\/p>\n\n

        \"Implementing<\/p>

        \n \n \n 測試\n<\/h2>\n\n

        幾秒鐘后,您將被重定向到登錄頁面。<\/p>\n\n

        \"Implementing<\/p>\n\n

        點擊登錄按鈕,您將登錄到主頁,主頁上會顯示登錄用戶的名字。<\/p>\n\n

        \"Implementing<\/p>\n\n

        嘗試刷新瀏覽器,您會看到您仍然處于登錄狀態(tài)。然后,按注銷按鈕,JWT 令牌將被刪除,您將再次重定向到登錄頁面。<\/p>\n\n

        \"Implementing<\/p>\n\n

        \n \n \n 結(jié)論\n<\/h2>\n\n

        總之,在 Go API 中實現(xiàn) JWT 身份驗證提供了一種安全且可擴展的方法來處理用戶身份驗證。通過使用 Gin 框架以及 golang-jwt\/jwt 包,我們可以輕松地將基于令牌的身份驗證集成到我們的應(yīng)用程序中。 JWT 令牌是在登錄期間生成的,用于安全地驗證用戶憑據(jù)并授予對受保護路由的訪問權(quán)限。中間件通過驗證令牌的有效性來確保只有經(jīng)過身份驗證的用戶才能訪問這些路由。這種無狀態(tài)身份驗證機制提供了增強的性能和靈活性,使其成為現(xiàn)代 API 架構(gòu)的理想選擇。<\/p>\n\n

        源代碼:https:\/\/github.com\/stackpuz\/Example-JWT-Go<\/p>\n\n

        在幾分鐘內(nèi)創(chuàng)建一個 CRUD Web 應(yīng)用程序:https:\/\/stackpuz.com<\/p>\n\n\n \n\n \n <\/pre><\/pre>"}

        首頁 后端開發(fā) Golang 在 Go API 中實現(xiàn) JWT 身份驗證

        在 Go API 中實現(xiàn) JWT 身份驗證

        Dec 27, 2024 pm 08:56 PM

        Implementing JWT Authentication in Go API

        JWT(JSON Web 令牌)是一種通過基于令牌的身份驗證保護 API 的高效方法,確保只有經(jīng)過身份驗證的用戶才能訪問您的 API 端點。與傳統(tǒng)的基于會話的方法不同,JWT 是無狀態(tài)的,無需服務(wù)器端會話存儲,這使其成為可擴展和高性能應(yīng)用程序的理想選擇。在本指南中,我們將引導(dǎo)您在 Go API 中實現(xiàn) JWT 身份驗證,從在用戶登錄時生成令牌到通過驗證這些令牌來保護您的端點,最終增強應(yīng)用程序數(shù)據(jù)和資源的安全性和穩(wěn)健性。

        先決條件

        • 去1.21

        設(shè)置項目

        go mod init app
        go get github.com/gin-gonic/gin@v1.5.0
        go get github.com/golang-jwt/jwt
        go get github.com/joho/godotenv 
        

        項目結(jié)構(gòu)

        ├─ .env
        ├─ main.go
        ├─ middleware
        │  └─ authenticate.go
        └─ public
           ├─ index.html
           └─ login.html
        

        項目文件

        .env

        jwt_secret = b0WciedNJvFCqFRbB2A1QhZoCDnutAOen5g1FEDO0HsLTwGINp04GXh2OXVpTqQL
        

        此 .env 文件包含一個環(huán)境變量 jwt_secret,它保存用于在應(yīng)用程序中簽名和驗證 JWT 令牌的密鑰。

        驗證.go

        package middleware
        
        import (
            "net/http"
            "os"
            "strings"
        
            "github.com/gin-gonic/gin"
            "github.com/golang-jwt/jwt"
        )
        
        type Claims struct {
            Id int `json:"id"`
            Name string `json:"name"`
            jwt.StandardClaims
        }
        
        func Authenticate() gin.HandlerFunc {
            return func(c *gin.Context) {
                if c.Request.URL.Path == "/" || c.Request.URL.Path == "/login" {
                    c.Next()
                    return
                }
                authHeader := c.GetHeader("Authorization")
                if authHeader == "" {
                    c.Status(http.StatusUnauthorized)
                    c.Abort()
                    return
                }
                tokenString := strings.TrimPrefix(authHeader, "Bearer ")
                token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
                    return []byte(os.Getenv("jwt_secret")), nil
                })
                if err != nil || !token.Valid {
                    c.Status(http.StatusUnauthorized)
                    c.Abort()
                    return
                }
                if claims, ok := token.Claims.(*Claims); ok {
                    c.Set("user", claims)
                } else {
                    c.Status(http.StatusUnauthorized)
                    c.Abort()
                    return
                }
                c.Next()
            }
        }
        

        authenticate.go 中間件使用 Gin 框架在 Go API 中定義了用于 JWT 身份驗證的函數(shù)。它檢查請求是否針對 / 或 /login 路徑,在這種情況下不需要身份驗證。對于其他路由,它會檢索授權(quán)標頭,并期望獲得承載令牌。使用 jwt 包和環(huán)境變量中的密鑰來解析和驗證令牌。如果令牌無效或丟失,請求將中止并顯示 401 未經(jīng)授權(quán)狀態(tài)。如果有效,則會提取用戶聲明(例如 id 和名稱)并將其添加到 Gin 上下文中,從而允許訪問受保護的路由。

        主程序

        package main
        
        import (
            "app/middleware"
            "net/http"
            "os"
            "time"
        
            "github.com/gin-gonic/gin"
            "github.com/golang-jwt/jwt"
            "github.com/joho/godotenv"
        )
        
        func main() {
            godotenv.Load()
            router := gin.Default()
            router.Use(middleware.Authenticate())
            router.LoadHTMLFiles("public/index.html", "public/login.html")
        
            router.GET("/", func(c *gin.Context) {
                c.HTML(http.StatusOK, "index.html", nil)
            })
        
            router.GET("/login", func(c *gin.Context) {
                c.HTML(http.StatusOK, "login.html", nil)
            })
        
            router.GET("/user", func(c *gin.Context) {
                user, _ := c.Get("user")
                claims := user.(*middleware.Claims)
                c.JSON(http.StatusOK, gin.H{"name": claims.Name})
            })
        
            router.POST("/login", func(c *gin.Context) {
                var login map[string]string
                c.BindJSON(&login)
                if login["name"] == "admin" && login["password"] == "1234" {
                    token := jwt.NewWithClaims(jwt.SigningMethodHS256, &middleware.Claims{
                        Id: 1,
                        Name: login["name"],
                        StandardClaims: jwt.StandardClaims{
                            IssuedAt: time.Now().Unix(),
                            ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
                        },
                    })
                    tokenString, _ := token.SignedString([]byte(os.Getenv("jwt_secret")))
                    c.JSON(http.StatusOK, gin.H{"token": tokenString})
                } else {
                    c.Status(http.StatusBadRequest)
                }
            })
            router.Run()
        }
        

        main.go 文件使用 Gin 框架設(shè)置 Go Web 服務(wù)器來處理基于 JWT 身份驗證的路由。它使用中間件進行身份驗證,檢查請求中的有效 JWT 令牌。服務(wù)器提供兩個 HTML 頁面:index.html 和 login.html,可通過 / 和 /login 路由訪問。

        對于 /user 路由,服務(wù)器從 JWT 聲明中檢索經(jīng)過身份驗證的用戶名,并在響應(yīng)中返回它。對于 /login POST 路由,服務(wù)器驗證用戶憑據(jù)(名稱和密碼),如果有效,則生成 JWT 令牌,使用密鑰對其進行簽名并將其發(fā)送回客戶端。服務(wù)器配置為偵聽請求并在默認端口上運行。

        索引.html

        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,initial-scale=1">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
        </head>
        <body>
            <div>
        
        
        
        <p>The index.html is a simple web page that provides a user interface for displaying the login status of a user. It uses Bootstrap for styling and Font Awesome for icons. On page load, it checks the user's authentication status by sending a request to the server with a JWT token stored in localStorage. If the user is logged in, it shows a success message with the user's name and a logout button. If not logged in, it shows a message indicating the user is not logged in and redirects them to the login page after a few seconds.</p>
        
        <h3>
          
          
          login.html
        </h3>
        
        
        
        <pre class="brush:php;toolbar:false"><!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,initial-scale=1">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
        </head>
        <body>
            <div>
        
        
        
        <p>The login.html page provides a simple login form where users can input their username and password. It uses Bootstrap for styling and Font Awesome for icons. When the user submits the form, a JavaScript function login() sends a POST request to the /login endpoint with the entered credentials. If the login is successful, the server returns a JWT token, which is stored in localStorage. The page then redirects the user to the home page (/). If the login fails, an error message is displayed.</p>
        
        <h2>
          
          
          Run project
        </h2>
        
        
        
        <pre class="brush:php;toolbar:false">go run main.go
        

        打開網(wǎng)絡(luò)瀏覽器并轉(zhuǎn)到http://localhost:8080

        你會發(fā)現(xiàn)這個測試頁。

        Implementing JWT Authentication in Go API

        測試

        幾秒鐘后,您將被重定向到登錄頁面。

        Implementing JWT Authentication in Go API

        點擊登錄按鈕,您將登錄到主頁,主頁上會顯示登錄用戶的名字。

        Implementing JWT Authentication in Go API

        嘗試刷新瀏覽器,您會看到您仍然處于登錄狀態(tài)。然后,按注銷按鈕,JWT 令牌將被刪除,您將再次重定向到登錄頁面。

        Implementing JWT Authentication in Go API

        結(jié)論

        總之,在 Go API 中實現(xiàn) JWT 身份驗證提供了一種安全且可擴展的方法來處理用戶身份驗證。通過使用 Gin 框架以及 golang-jwt/jwt 包,我們可以輕松地將基于令牌的身份驗證集成到我們的應(yīng)用程序中。 JWT 令牌是在登錄期間生成的,用于安全地驗證用戶憑據(jù)并授予對受保護路由的訪問權(quán)限。中間件通過驗證令牌的有效性來確保只有經(jīng)過身份驗證的用戶才能訪問這些路由。這種無狀態(tài)身份驗證機制提供了增強的性能和靈活性,使其成為現(xiàn)代 API 架構(gòu)的理想選擇。

        源代碼:https://github.com/stackpuz/Example-JWT-Go

        在幾分鐘內(nèi)創(chuàng)建一個 CRUD Web 應(yīng)用程序:https://stackpuz.com

        以上是在 Go API 中實現(xiàn) JWT 身份驗證的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

        本站聲明
        本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

        熱AI工具

        Undress AI Tool

        Undress AI Tool

        免費脫衣服圖片

        Undresser.AI Undress

        Undresser.AI Undress

        人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

        AI Clothes Remover

        AI Clothes Remover

        用于從照片中去除衣服的在線人工智能工具。

        Clothoff.io

        Clothoff.io

        AI脫衣機

        Video Face Swap

        Video Face Swap

        使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

        熱工具

        記事本++7.3.1

        記事本++7.3.1

        好用且免費的代碼編輯器

        SublimeText3漢化版

        SublimeText3漢化版

        中文版,非常好用

        禪工作室 13.0.1

        禪工作室 13.0.1

        功能強大的PHP集成開發(fā)環(huán)境

        Dreamweaver CS6

        Dreamweaver CS6

        視覺化網(wǎng)頁開發(fā)工具

        SublimeText3 Mac版

        SublimeText3 Mac版

        神級代碼編輯軟件(SublimeText3)

        熱門話題

        Laravel 教程
        1597
        29
        PHP教程
        1488
        72
        是Golang前端還是后端 是Golang前端還是后端 Jul 08, 2025 am 01:44 AM

        Golang主要用于后端開發(fā),但也能在前端領(lǐng)域間接發(fā)揮作用。其設(shè)計目標聚焦高性能、并發(fā)處理和系統(tǒng)級編程,適合構(gòu)建API服務(wù)器、微服務(wù)、分布式系統(tǒng)、數(shù)據(jù)庫操作及CLI工具等后端應(yīng)用。雖然Golang不是網(wǎng)頁前端的主流語言,但可通過GopherJS編譯成JavaScript、通過TinyGo運行于WebAssembly,或搭配模板引擎生成HTML頁面來參與前端開發(fā)。然而,現(xiàn)代前端開發(fā)仍需依賴JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能后端為核心的技術(shù)棧選擇。

        如何在Golang中構(gòu)建GraphQl API 如何在Golang中構(gòu)建GraphQl API Jul 08, 2025 am 01:03 AM

        要構(gòu)建一個GraphQLAPI在Go語言中,推薦使用gqlgen庫以提高開發(fā)效率。1.首先選擇合適的庫,如gqlgen,它支持根據(jù)schema自動生成代碼;2.接著定義GraphQLschema,描述API的結(jié)構(gòu)和查詢?nèi)肟?,如定義Post類型和查詢方法;3.然后初始化項目并生成基礎(chǔ)代碼,實現(xiàn)resolver中的業(yè)務(wù)邏輯;4.最后將GraphQLhandler接入HTTPserver,通過內(nèi)置Playground測試API。注意事項包括字段命名規(guī)范、錯誤處理、性能優(yōu)化及安全設(shè)置等,確保項目可維護性

        如何安裝去 如何安裝去 Jul 09, 2025 am 02:37 AM

        安裝Go的關(guān)鍵在于選擇正確版本、配置環(huán)境變量并驗證安裝。1.前往官網(wǎng)下載對應(yīng)系統(tǒng)的安裝包,Windows使用.msi文件,macOS使用.pkg文件,Linux使用.tar.gz文件并解壓至/usr/local目錄;2.配置環(huán)境變量,在Linux/macOS中編輯~/.bashrc或~/.zshrc添加PATH和GOPATH,Windows則在系統(tǒng)屬性中設(shè)置PATH為Go的安裝路徑;3.使用goversion命令驗證安裝,并運行測試程序hello.go確認編譯執(zhí)行正常。整個流程中PATH設(shè)置和環(huán)

        Go Sync.WaitGroup示例 Go Sync.WaitGroup示例 Jul 09, 2025 am 01:48 AM

        sync.WaitGroup用于等待一組goroutine完成任務(wù),其核心是通過Add、Done、Wait三個方法協(xié)同工作。1.Add(n)設(shè)置需等待的goroutine數(shù)量;2.Done()在每個goroutine結(jié)束時調(diào)用,計數(shù)減一;3.Wait()阻塞主協(xié)程直到所有任務(wù)完成。使用時需注意:Add應(yīng)在goroutine外調(diào)用、避免重復(fù)Wait、務(wù)必確保Done被調(diào)用,推薦配合defer使用。常見于并發(fā)抓取網(wǎng)頁、批量數(shù)據(jù)處理等場景,能有效控制并發(fā)流程。

        去嵌入軟件包教程 去嵌入軟件包教程 Jul 09, 2025 am 02:46 AM

        使用Go的embed包可以方便地將靜態(tài)資源嵌入二進制,適合Web服務(wù)打包HTML、CSS、圖片等文件。1.聲明嵌入資源需在變量前加//go:embed注釋,如嵌入單個文件hello.txt;2.可嵌入整個目錄如static/*,通過embed.FS實現(xiàn)多文件打包;3.開發(fā)時建議通過buildtag或環(huán)境變量切換磁盤加載模式以提高效率;4.注意路徑正確性、文件大小限制及嵌入資源的只讀特性。合理使用embed能簡化部署并優(yōu)化項目結(jié)構(gòu)。

        進行音頻/視頻處理 進行音頻/視頻處理 Jul 20, 2025 am 04:14 AM

        音視頻處理的核心在于理解基本流程與優(yōu)化方法。1.其基本流程包括采集、編碼、傳輸、解碼和播放,每個環(huán)節(jié)均有技術(shù)難點;2.常見問題如音畫不同步、卡頓延遲、聲音噪音、畫面模糊等,可通過同步調(diào)整、編碼優(yōu)化、降噪模塊、參數(shù)調(diào)節(jié)等方式解決;3.推薦使用FFmpeg、OpenCV、WebRTC、GStreamer等工具實現(xiàn)功能;4.性能管理方面應(yīng)注重硬件加速、合理設(shè)置分辨率幀率、控制并發(fā)及內(nèi)存泄漏問題。掌握這些關(guān)鍵點有助于提升開發(fā)效率和用戶體驗。

        如何在GO中構(gòu)建Web服務(wù)器 如何在GO中構(gòu)建Web服務(wù)器 Jul 15, 2025 am 03:05 AM

        搭建一個用Go編寫的Web服務(wù)器并不難,核心在于利用net/http包實現(xiàn)基礎(chǔ)服務(wù)。1.使用net/http啟動最簡服務(wù)器:通過幾行代碼注冊處理函數(shù)并監(jiān)聽端口;2.路由管理:使用ServeMux組織多個接口路徑,便于結(jié)構(gòu)化管理;3.常見做法:按功能模塊分組路由,并可用第三方庫支持復(fù)雜匹配;4.靜態(tài)文件服務(wù):通過http.FileServer提供HTML、CSS和JS文件;5.性能與安全:啟用HTTPS、限制請求體大小、設(shè)置超時時間以提升安全性與性能。掌握這些要點后,擴展功能將更加容易。

        使用默認情況選擇 使用默認情況選擇 Jul 14, 2025 am 02:54 AM

        select加default的作用是讓select在沒有其他分支就緒時執(zhí)行默認行為,避免程序阻塞。1.非阻塞地從channel接收數(shù)據(jù)時,若channel為空,會直接進入default分支;2.結(jié)合time.After或ticker定時嘗試發(fā)送數(shù)據(jù),若channel滿則不阻塞而跳過;3.防止死鎖,在不確定channel是否被關(guān)閉時避免程序卡住;使用時需注意default分支會立即執(zhí)行,不能濫用,且default與case互斥,不會同時執(zhí)行。

        See all articles