2016-01-25 20:29:20 -05:00
|
|
|
/*
|
|
|
|
* Minio Cloud Storage, (C) 2016 Minio, Inc.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2016-01-21 19:28:15 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2016-01-25 01:26:53 -05:00
|
|
|
jwtgo "github.com/dgrijalva/jwt-go"
|
2016-01-21 19:28:15 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type authHandler struct {
|
|
|
|
handler http.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
// AuthHandler -
|
2016-01-25 20:29:20 -05:00
|
|
|
// Verify if authorization header is of form JWT, reject it otherwise.
|
2016-01-21 19:28:15 -05:00
|
|
|
func AuthHandler(h http.Handler) http.Handler {
|
|
|
|
return authHandler{h}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ignore request if authorization header is not valid.
|
|
|
|
func (h authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2016-01-23 22:44:32 -05:00
|
|
|
// Let the top level caller handle if the requests should be
|
2016-01-25 20:29:20 -05:00
|
|
|
// allowed, if there are no Authorization headers.
|
2016-01-23 22:44:32 -05:00
|
|
|
if r.Header.Get("Authorization") == "" {
|
2016-01-21 19:28:15 -05:00
|
|
|
h.handler.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
2016-01-25 20:29:20 -05:00
|
|
|
// Validate Authorization header to be valid.
|
2016-01-25 01:26:53 -05:00
|
|
|
jwt := InitJWT()
|
2016-01-27 04:52:54 -05:00
|
|
|
token, e := jwtgo.ParseFromRequest(r, func(token *jwtgo.Token) (interface{}, error) {
|
|
|
|
if _, ok := token.Method.(*jwtgo.SigningMethodHMAC); !ok {
|
2016-01-21 19:28:15 -05:00
|
|
|
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
|
|
|
}
|
2016-01-27 04:52:54 -05:00
|
|
|
return jwt.secretAccessKey, nil
|
2016-01-21 19:28:15 -05:00
|
|
|
})
|
2016-01-27 04:52:54 -05:00
|
|
|
if e != nil || !token.Valid {
|
2016-01-21 19:28:15 -05:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
h.handler.ServeHTTP(w, r)
|
|
|
|
}
|