41 lines
956 B
Go
41 lines
956 B
Go
package auth
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestHashCheck(t *testing.T) {
|
|
h, err := HashPassword("hunter2")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.HasPrefix(h, "$2a$") || !CheckPassword(h, "hunter2") || CheckPassword(h, "wrong") {
|
|
t.Fatal("bcrypt wrong")
|
|
}
|
|
}
|
|
|
|
func TestSignParse(t *testing.T) {
|
|
secret := []byte("k")
|
|
tok, err := Sign(secret, 7, "admin")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c, err := Parse(secret, tok)
|
|
if err != nil || c.UID != 7 || c.Role != "admin" {
|
|
t.Fatalf("parse: %v %+v", err, c)
|
|
}
|
|
if _, err := Parse([]byte("other"), tok); err == nil {
|
|
t.Fatal("must reject wrong secret")
|
|
}
|
|
expired, _ := SignWithTTL(secret, 1, "member", -time.Hour)
|
|
if _, err := Parse(secret, expired); err == nil {
|
|
t.Fatal("must reject expired")
|
|
}
|
|
// alg 混淆攻击:none 必须拒
|
|
if _, err := Parse(secret, "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1aWQiOjF9."); err == nil {
|
|
t.Fatal("must reject alg=none")
|
|
}
|
|
}
|