Simplified authentication negotiation

This commit is contained in:
Andreas Schneider 2018-04-03 12:12:50 +02:00
parent a739a9b4bb
commit 7ca7675a85
1 changed files with 20 additions and 22 deletions

View File

@ -66,28 +66,24 @@ type EWSRoundTripper struct {
} }
func (er EWSRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { func (er EWSRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if er.authType == authTypeBasic {
r.SetBasicAuth(er.username, er.password)
}
er.initMutex.Lock() er.initMutex.Lock()
resp, err := er.delegate.RoundTrip(r) if er.authType == authTypeUnknown {
if err == nil && resp.StatusCode == http.StatusUnauthorized && er.authType == authTypeUnknown { // Find authentication scheme.
// This is a good time to find out what the server prefers. resp, err := http.DefaultClient.Get(r.URL.String())
authHeaders := resp.Header["Www-Authenticate"] if err == nil && resp.StatusCode == http.StatusUnauthorized {
if authHeaders != nil { // This is a good time to find out what the server prefers.
for _, h := range authHeaders { authHeaders := resp.Header["Www-Authenticate"]
if strings.HasPrefix(h, "BASIC") { if authHeaders != nil {
er.authType = authTypeBasic for _, h := range authHeaders {
} else if strings.HasPrefix(h, "NTLM") { if strings.HasPrefix(h, "BASIC") {
er.authType = authTypeNTLM er.authType = authTypeBasic
break // NTLM is the best we could do } else if strings.HasPrefix(h, "NTLM") {
er.authType = authTypeNTLM
break // NTLM is the best we could do
}
} }
} }
}
// So, do we know more than before? If so, try again.
if er.authType > authTypeUnknown {
if er.authType == authTypeNTLM { if er.authType == authTypeNTLM {
// We need to replace the delegator. // We need to replace the delegator.
er.delegate = &httpntlm.NtlmTransport{ er.delegate = &httpntlm.NtlmTransport{
@ -96,13 +92,15 @@ func (er EWSRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
Password: er.password, Password: er.password,
} }
} }
er.initMutex.Unlock()
return er.RoundTrip(r)
} }
} }
er.initMutex.Unlock() er.initMutex.Unlock()
return resp, err
if er.authType == authTypeBasic {
r.SetBasicAuth(er.username, er.password)
}
return er.delegate.RoundTrip(r)
} }
func NewEWSCalendar(url, username, password string) *EWSCalendar { func NewEWSCalendar(url, username, password string) *EWSCalendar {