Skip to content

Commit a88e269

Browse files
authored
Merge pull request #11 from aryan9600/bearer
add support for bearer token auth
2 parents 96e4120 + 9780c7d commit a88e269

File tree

3 files changed

+22
-23
lines changed

3 files changed

+22
-23
lines changed

credential.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
package gitkit
22

33
import (
4-
"fmt"
54
"net/http"
65
)
76

87
type Credential struct {
9-
Username string
10-
Password string
8+
Username string
9+
Password string
10+
Authorization string
1111
}
1212

13-
func getCredential(req *http.Request) (Credential, error) {
13+
func getCredential(req *http.Request) Credential {
1414
cred := Credential{}
1515

16-
user, pass, ok := req.BasicAuth()
17-
if !ok {
18-
return cred, fmt.Errorf("authentication failed")
19-
}
16+
user, pass, _ := req.BasicAuth()
17+
18+
auth := req.Header.Get("Authorization")
2019

2120
cred.Username = user
2221
cred.Password = pass
22+
cred.Authorization = auth
2323

24-
return cred, nil
24+
return cred
2525
}

credential_test.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,20 @@ import (
99

1010
func Test_getCredential(t *testing.T) {
1111
req, _ := http.NewRequest("get", "http://localhost", nil)
12-
_, err := getCredential(req)
13-
assert.Error(t, err)
14-
assert.Equal(t, "authentication failed", err.Error())
12+
cred := getCredential(req)
13+
assert.Equal(t, cred.Authorization, "")
1514

1615
req, _ = http.NewRequest("get", "http://localhost", nil)
1716
req.SetBasicAuth("Alladin", "OpenSesame")
18-
cred, err := getCredential(req)
17+
cred = getCredential(req)
1918

20-
assert.NoError(t, err)
2119
assert.Equal(t, "Alladin", cred.Username)
2220
assert.Equal(t, "OpenSesame", cred.Password)
21+
assert.Contains(t, cred.Authorization, "Basic ")
22+
23+
req, _ = http.NewRequest("get", "http://localhost", nil)
24+
req.Header.Add("Authorization", "Bearer VerySecretToken")
25+
cred = getCredential(req)
26+
27+
assert.Equal(t, "Bearer VerySecretToken", cred.Authorization)
2328
}

http.go

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -88,20 +88,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
8888
return
8989
}
9090

91-
authHeader := r.Header.Get("Authorization")
92-
if authHeader == "" {
91+
cred := getCredential(r)
92+
if cred.Authorization == "" {
93+
logError("auth", fmt.Errorf("no Authorization header found"))
9394
w.Header()["WWW-Authenticate"] = []string{`Basic realm=""`}
9495
w.WriteHeader(http.StatusUnauthorized)
9596
return
9697
}
9798

98-
cred, err := getCredential(r)
99-
if err != nil {
100-
logError("auth", err)
101-
w.WriteHeader(http.StatusUnauthorized)
102-
return
103-
}
104-
10599
allow, err := s.AuthFunc(cred, req)
106100
if !allow || err != nil {
107101
if err != nil {

0 commit comments

Comments
 (0)