Skip to content

Commit

Permalink
CORS checking added, cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
ajmyyra committed Sep 23, 2018
1 parent 85b28bb commit 43dd5ae
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 47 deletions.
47 changes: 1 addition & 46 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"reflect"
"strings"
"time"

"github.com/dgrijalva/jwt-go"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-redis/redis"
)

Expand All @@ -25,8 +22,6 @@ var redisdb *redis.Client
var logoutCookie = false

var nonceChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var hmacSecret []byte

var blacklist []string

type blacklistItem struct {
Expand All @@ -49,11 +44,6 @@ func init() {
log.Fatal("Problem connecting to Redis: ", err.Error())
}

rand.Seed(time.Now().UnixNano())

// 64 char(512 bit) key is needed for HS512
hmacSecret = initialiseHMACSecretFromEnv("JWT_HMAC_SECRET", 64)

envContent := os.Getenv("LOGOUT_COOKIE")
if envContent == "true" {
logoutCookie = true
Expand All @@ -79,8 +69,6 @@ func newWildcardHandler() *wildcardHandler {

// AuthReqHandler processes all incoming requests by default, unless specific endpoint is mentioned
func AuthReqHandler(w http.ResponseWriter, r *http.Request) {
// TODO CORS check, others?

cookie, err := r.Cookie("auth")
if err != nil {
log.Println(getUserIP(r), r.URL.String(), "Cookie not set, redirecting to login.")
Expand All @@ -92,8 +80,6 @@ func AuthReqHandler(w http.ResponseWriter, r *http.Request) {
log.Println(getUserIP(r), r.URL.String(), "Empty authorization header.")
returnStatus(w, http.StatusBadRequest, "Cookie empty or malformed.")
} else {
// TODO check JWT validation and ditch Redis

token, err := parseJWT(cookie.Value)
if err != nil {
if err.Error() == "Token is expired" {
Expand Down Expand Up @@ -183,26 +169,6 @@ func returnStatus(w http.ResponseWriter, statusCode int, errorMsg string) {
w.Write([]byte(errorMsg))
}

func parseJWT(tokenstr string) (*jwt.Token, error) {
token, err := jwt.Parse(tokenstr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}

return hmacSecret, nil
})

if err != nil {
return nil, err
}

if token.Valid {
return token, nil
}

return nil, errors.New("Token not valid")
}

func getUserIP(r *http.Request) string {
headerIP := r.Header.Get("X-Forwarded-For")
if headerIP != "" {
Expand Down Expand Up @@ -232,17 +198,6 @@ func base64decode(str string) ([]byte, error) {
return arr, nil
}

func initialiseHMACSecretFromEnv(secEnv string, reqLen int) []byte {
envContent := os.Getenv(secEnv)

if len(envContent) < reqLen {
log.Println("WARNING: HMAC secret not provided or secret too short. Generating a random one from nonce characters.")
return []byte(createNonce(reqLen))
}

return []byte(envContent)
}

func updateBlacklist() {
res, err := redisdb.HVals("blacklist").Result()
if err != nil {
Expand Down
41 changes: 41 additions & 0 deletions login.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"strings"
"time"

Expand All @@ -20,6 +23,8 @@ var oauth2Config oauth2.Config
var oidcProvider *oidc.Provider
var oidcConfig *oidc.Config

var hmacSecret []byte

func init() {
hostname = strings.Split(parseEnvURL("SELF_URL").Host, ":")[0] // Because Host still has a port if it was in URL

Expand Down Expand Up @@ -57,6 +62,11 @@ func init() {
}

oidcProvider = provider

rand.Seed(time.Now().UnixNano())

// 64 char(512 bit) key is needed for HS512
hmacSecret = initialiseHMACSecretFromEnv("JWT_HMAC_SECRET", 64)
}

// OIDCHandler processes authn responses from OpenID Provider, exchanges token to userinfo and establishes user session with cookie containing JWT token
Expand Down Expand Up @@ -183,3 +193,34 @@ func createNonce(length int) string {

return string(nonce)
}

func parseJWT(tokenstr string) (*jwt.Token, error) {
token, err := jwt.Parse(tokenstr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}

return hmacSecret, nil
})

if err != nil {
return nil, err
}

if token.Valid {
return token, nil
}

return nil, errors.New("Token not valid")
}

func initialiseHMACSecretFromEnv(secEnv string, reqLen int) []byte {
envContent := os.Getenv(secEnv)

if len(envContent) < reqLen {
log.Println("WARNING: HMAC secret not provided or secret too short. Generating a random one from nonce characters.")
return []byte(createNonce(reqLen))
}

return []byte(envContent)
}
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"time"

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)

Expand Down Expand Up @@ -66,5 +67,5 @@ func main() {
updateBlacklist()
go scheduleBlacklistUpdater(60)

log.Fatal(http.ListenAndServe(":8080", router))
log.Fatal(http.ListenAndServe(":8080", handlers.CORS()(router)))
}

0 comments on commit 43dd5ae

Please sign in to comment.