欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

golang進行簡單權(quán)限認證的實現(xiàn)

 更新時間:2021年09月23日 11:37:24   作者:wilson_go  
本文主要介紹了golang簡單權(quán)限認證的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

使用JWT進行認證

JSON Web Tokens (JWT) are a more modern approach to authentication.

As the web moves to a greater separation between the client and server, JWT provides a wonderful alternative to traditional cookie based authentication models.

JWTs provide a way for clients to authenticate every request without having to maintain a session or repeatedly pass login credentials to the server.

用戶注冊之后, 服務(wù)器生成一個 JWT token返回給瀏覽器, 瀏覽器向服務(wù)器請求數(shù)據(jù)時將 JWT token 發(fā)給服務(wù)器, 服務(wù)器用 signature 中定義的方式解碼

JWT 獲取用戶信息.

一個 JWT token包含3部分:
1 header: 告訴我們使用的算法和 token 類型
2 Payload: 必須使用 sub key 來指定用戶 ID, 還可以包括其他信息比如 email, username 等.
3 Signature: 用來保證 JWT 的真實性. 可以使用不同算法

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/codegangsta/negroni"
	"github.com/dgrijalva/jwt-go"
	"github.com/dgrijalva/jwt-go/request"
)
const (
	SecretKey = "welcome ---------"
)

func fatal(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

type UserCredentials struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type User struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Username string `json:"username"`
	Password string `json:"password"`
}

type Response struct {
	Data string `json:"data"`
}

type Token struct {
	Token string `json:"token"`
}

func StartServer() {

	http.HandleFunc("/login", LoginHandler)

	http.Handle("/resource", negroni.New(
		negroni.HandlerFunc(ValidateTokenMiddleware),
		negroni.Wrap(http.HandlerFunc(ProtectedHandler)),
	))

	log.Println("Now listening...")
	http.ListenAndServe(":8087", nil)
}

func main() {
	StartServer()
}

func ProtectedHandler(w http.ResponseWriter, r *http.Request) {

	response := Response{"Gained access to protected resource"}
	JsonResponse(response, w)

}

func LoginHandler(w http.ResponseWriter, r *http.Request) {

	var user UserCredentials

	err := json.NewDecoder(r.Body).Decode(&user)

	if err != nil {
		w.WriteHeader(http.StatusForbidden)
		fmt.Fprint(w, "Error in request")
		return
	}

	if strings.ToLower(user.Username) != "someone" {
		if user.Password != "p@ssword" {
			w.WriteHeader(http.StatusForbidden)
			fmt.Println("Error logging in")
			fmt.Fprint(w, "Invalid credentials")
			return
		}
	}

	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
	claims["iat"] = time.Now().Unix()
	token.Claims = claims

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintln(w, "Error extracting the key")
		fatal(err)
	}

	tokenString, err := token.SignedString([]byte(SecretKey))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintln(w, "Error while signing the token")
		fatal(err)
	}

	response := Token{tokenString}
	JsonResponse(response, w)

}

func ValidateTokenMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {

	token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(SecretKey), nil
		})

	if err == nil {
		if token.Valid {
			next(w, r)
		} else {
			w.WriteHeader(http.StatusUnauthorized)
			fmt.Fprint(w, "Token is not valid")
		}
	} else {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(w, "Unauthorized access to this resource")
	}

}

func JsonResponse(response interface{}, w http.ResponseWriter) {

	json, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	w.Write(json)
}

在這里插入圖片描述

在這里插入圖片描述

到此這篇關(guān)于golang進行簡單權(quán)限認證的實現(xiàn)的文章就介紹到這了,更多相關(guān)golang 權(quán)限認證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 讓GPT教你用go語言和C語言開發(fā)IDE配置學(xué)習(xí)

    讓GPT教你用go語言和C語言開發(fā)IDE配置學(xué)習(xí)

    這篇文章主要介紹了讓GPT教你用go語言和C語言開發(fā)IDE配置學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-10-10
  • golang如何使用gomobile進行Android開發(fā)

    golang如何使用gomobile進行Android開發(fā)

    golang可以開發(fā)android,使用golang開發(fā)android需要下載安裝gomobile,下面這篇文章主要給大家介紹了關(guān)于golang如何使用gomobile進行Android開發(fā)的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • go開發(fā)中引用靜態(tài)庫.a文件的方法

    go開發(fā)中引用靜態(tài)庫.a文件的方法

    這篇文章主要介紹了go開發(fā)中引用靜態(tài)庫.a文件的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Go?語言使用goroutine運行閉包踩坑分析

    Go?語言使用goroutine運行閉包踩坑分析

    這篇文章主要介紹了Go?語言使用goroutine運行閉包踩坑解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-11-11
  • Prometheus Go client library使用方式詳解

    Prometheus Go client library使用方式詳解

    這篇文章主要為大家介紹了Prometheus Go client library使用方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-11-11
  • go語言中g(shù)orm時間格式化

    go語言中g(shù)orm時間格式化

    本文主要介紹了go語言中g(shù)orm時間格式化,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 使用Golang采集Nginx接口流量大小的步驟

    使用Golang采集Nginx接口流量大小的步驟

    在開發(fā)和運維中,我們經(jīng)常需要監(jiān)控和分析服務(wù)器的接口流量大小,特別是對于部署了 Nginx 的服務(wù)器,本文將介紹如何使用 Golang 采集 Nginx 接口流量大小,并展示如何將這些數(shù)據(jù)進行實時監(jiān)控和分析
    2023-11-11
  • 使用go實現(xiàn)常見的數(shù)據(jù)結(jié)構(gòu)

    使用go實現(xiàn)常見的數(shù)據(jù)結(jié)構(gòu)

    這篇文章主要介紹了使用go實現(xiàn)常見的數(shù)據(jù)結(jié)構(gòu),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • Golang實現(xiàn)Directional Channel(定向通道)

    Golang實現(xiàn)Directional Channel(定向通道)

    這篇文章主要介紹了Golang實現(xiàn)Directional Channel(定向通道),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Golang的os標(biāo)準庫中常用函數(shù)的整理介紹

    Golang的os標(biāo)準庫中常用函數(shù)的整理介紹

    這篇文章主要介紹了Go語言的os標(biāo)準庫中常用函數(shù),主要用來實現(xiàn)與操作系統(tǒng)的交互功能,需要的朋友可以參考下
    2015-10-10

最新評論