5
0
Fork 0

Use RSA instead of HMAC. Fixes #1

master
Daniel Lim 2019-06-23 06:37:30 +08:00
parent 26834cf938
commit 78cd136987
2 changed files with 16 additions and 5 deletions

1
.env
View File

@ -1,2 +1 @@
LISTEN=127.0.0.1:3000 LISTEN=127.0.0.1:3000
SECRET=secret

20
main.go
View File

@ -1,8 +1,10 @@
package main package main
import ( import (
"crypto/rsa"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@ -15,7 +17,7 @@ import (
) )
var listen string var listen string
var secret []byte var publicKey *rsa.PublicKey
func main() { func main() {
// Load .env // Load .env
@ -24,7 +26,17 @@ func main() {
log.Fatal("Error loading .env file") log.Fatal("Error loading .env file")
} }
listen = os.Getenv("LISTEN") listen = os.Getenv("LISTEN")
secret = []byte(os.Getenv("SECRET"))
// Load RSA public key
publicKeyBytes, err := ioutil.ReadFile("key.pub")
if err != nil {
log.Fatal(err)
}
publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicKeyBytes)
if err != nil {
log.Fatal(err)
}
// Routes // Routes
router := httprouter.New() router := httprouter.New()
@ -81,10 +93,10 @@ func Auth(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Parse token // Parse token
token, err := jwt.Parse(tokenString, func (token *jwt.Token) (interface{}, error) { token, err := jwt.Parse(tokenString, func (token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
} }
return secret, nil return publicKey, nil
}) })
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)