欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

golang进行简单权限认证的实现

程序员文章站 2022-06-16 22:17:53
使用jwt进行认证json web tokens (jwt) are a more modern approach to authentication.as the web moves to a gr...

使用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.

用户注册之后, 服务器生成一个 jwt token返回给浏览器, 浏览器向服务器请求数据时将 jwt token 发给服务器, 服务器用 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)
}

golang进行简单权限认证的实现

golang进行简单权限认证的实现

到此这篇关于golang进行简单权限认证的实现的文章就介绍到这了,更多相关golang 权限认证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: golang 权限认证