Changing JWT to use certificates
This commit is contained in:
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"libshared"
|
||||
@@ -21,6 +22,8 @@ type AuthenticateResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
var privateKey *rsa.PrivateKey
|
||||
|
||||
func authenticateHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var authenticaterequest AuthenticateRequest
|
||||
@@ -29,7 +32,7 @@ func authenticateHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var hashText string
|
||||
var ok bool
|
||||
var token string
|
||||
secret := []byte("super-secret-key")
|
||||
//secret := []byte("super-secret-key")
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
// Only allow POST method
|
||||
@@ -102,7 +105,7 @@ func authenticateHandler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
token, err = createJWT(secret, fmt.Sprintf("%d", authenticaterequest.Accountid), authenticaterequest.Username, "user")
|
||||
token, err = libshared.CreateJWT(privateKey, fmt.Sprintf("%d", authenticaterequest.Accountid), authenticaterequest.Username, "user")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
apiresponse := libshared.NewAPIResponse("fail", "Failed to create JWT", AuthenticateResponse{})
|
||||
|
||||
22
jwt.go
22
jwt.go
@@ -1,22 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// CreateJWT generates a signed JWT
|
||||
func createJWT(secret []byte, account string, user string, purpose string) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"sub": user, // subject (user id)
|
||||
"exp": time.Now().Add(time.Hour).Unix(), // expiration
|
||||
"iat": time.Now().Unix(), // issued at
|
||||
"purpose": purpose,
|
||||
"account": account,
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
return token.SignedString(secret)
|
||||
}
|
||||
6
main.go
6
main.go
@@ -20,7 +20,13 @@ func decodeHash(encoded string) (*argonParams, []byte, []byte, error) {
|
||||
}
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
|
||||
libshared.Pool = libshared.GetDbPool()
|
||||
privateKey, err = libshared.LoadPrivateKey("keys/private.pem")
|
||||
if err != nil {
|
||||
log.Fatal("Failed to load private key:", err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/identity/create-local-identity", createLocalHandler)
|
||||
http.HandleFunc("/identity/authenticate", authenticateHandler)
|
||||
|
||||
Reference in New Issue
Block a user