Returns HTTP unauthorized for ajax requests instead of redirecting to the sing-in page

This commit is contained in:
Cosmin Cojocar
2019-01-31 16:23:01 +01:00
parent 01c5f5ae3b
commit c12db0ebf7
2 changed files with 92 additions and 0 deletions
+28
View File
@@ -754,6 +754,8 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
} else {
p.SignInPage(rw, req, http.StatusForbidden)
}
} else if status == http.StatusUnauthorized {
p.ErrorJSON(rw, status)
} else {
p.serveMux.ServeHTTP(rw, req)
}
@@ -826,6 +828,11 @@ func (p *OAuthProxy) Authenticate(rw http.ResponseWriter, req *http.Request) int
}
if session == nil {
// Check if is an ajax request and return unauthorized to avoid a redirect
// to the login page
if p.isAjax(req) {
return http.StatusUnauthorized
}
return http.StatusForbidden
}
@@ -894,3 +901,24 @@ func (p *OAuthProxy) CheckBasicAuth(req *http.Request) (*providers.SessionState,
}
return nil, fmt.Errorf("%s not in HtpasswdFile", pair[0])
}
// isAjax checks if a request is an ajax request
func (p *OAuthProxy) isAjax(req *http.Request) bool {
acceptValues, ok := req.Header["accept"]
if !ok {
acceptValues = req.Header["Accept"]
}
const ajaxReq = "application/json"
for _, v := range acceptValues {
if v == ajaxReq {
return true
}
}
return false
}
// ErrorJSON returns the error code witht an application/json mime type
func (p *OAuthProxy) ErrorJSON(rw http.ResponseWriter, code int) {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
}