1JWT middleware for go gonic.
2
3JSON Web Token (JWT) more information: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
4
5EDIT: Below is the test for [christopherL91/Go-API](https://github.com/christopherL91/Go-API)
6
7```go
8package jwt_test
9
10import (
11 "encoding/json"
12 . "github.com/smartystreets/goconvey/convey"
13 "io/ioutil"
14 "net/http"
15 "strings"
16 "testing"
17)
18
19type User struct {
20 Username string `json:"username"`
21 Password string `json:"password"`
22}
23
24type Response struct {
25 Token string `json:"token"`
26}
27
28func createNewsUser(username, password string) *User {
29 return &User{username, password}
30}
31
32func TestLogin(t *testing.T) {
33 Convey("Should be able to login", t, func() {
34 user := createNewsUser("jonas", "1234")
35 jsondata, _ := json.Marshal(user)
36 post_data := strings.NewReader(string(jsondata))
37 req, _ := http.NewRequest("POST", "http://localhost:3000/api/login", post_data)
38 req.Header.Set("Content-Type", "application/json")
39 client := &http.Client{}
40 res, _ := client.Do(req)
41 So(res.StatusCode, ShouldEqual, 200)
42
43 Convey("Should be able to parse body", func() {
44 body, err := ioutil.ReadAll(res.Body)
45 defer res.Body.Close()
46 So(err, ShouldBeNil)
47 Convey("Should be able to get json back", func() {
48 responseData := new(Response)
49 err := json.Unmarshal(body, responseData)
50 So(err, ShouldBeNil)
51
52 Convey("Should be able to be authorized", func() {
53 token := responseData.Token
54 req, _ := http.NewRequest("GET", "http://localhost:3000/api/auth/testAuth", nil)
55 req.Header.Set("Authorization", "Bearer "+token)
56 client = &http.Client{}
57 res, _ := client.Do(req)
58 So(res.StatusCode, ShouldEqual, 200)
59 })
60 })
61 })
62 })
63 Convey("Should not be able to login with false credentials", t, func() {
64 user := createNewsUser("jnwfkjnkfneknvjwenv", "wenknfkwnfknfknkfjnwkfenw")
65 jsondata, _ := json.Marshal(user)
66 post_data := strings.NewReader(string(jsondata))
67 req, _ := http.NewRequest("POST", "http://localhost:3000/api/login", post_data)
68 req.Header.Set("Content-Type", "application/json")
69 client := &http.Client{}
70 res, _ := client.Do(req)
71 So(res.StatusCode, ShouldEqual, 401)
72 })
73
74 Convey("Should not be able to authorize with false credentials", t, func() {
75 token := ""
76 req, _ := http.NewRequest("GET", "http://localhost:3000/api/auth/testAuth", nil)
77 req.Header.Set("Authorization", "Bearer "+token)
78 client := &http.Client{}
79 res, _ := client.Do(req)
80 So(res.StatusCode, ShouldEqual, 401)
81 })
82}
83```
View as plain text