From 7ca7675a85095023feb5cc6487b634ba1f5075d1 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 3 Apr 2018 12:12:50 +0200 Subject: [PATCH] Simplified authentication negotiation --- src/calanonsync/ews.go | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/calanonsync/ews.go b/src/calanonsync/ews.go index e44ce43..4b0f797 100644 --- a/src/calanonsync/ews.go +++ b/src/calanonsync/ews.go @@ -66,28 +66,24 @@ type EWSRoundTripper struct { } func (er EWSRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - if er.authType == authTypeBasic { - r.SetBasicAuth(er.username, er.password) - } - er.initMutex.Lock() - resp, err := er.delegate.RoundTrip(r) - if err == nil && resp.StatusCode == http.StatusUnauthorized && er.authType == authTypeUnknown { - // This is a good time to find out what the server prefers. - authHeaders := resp.Header["Www-Authenticate"] - if authHeaders != nil { - for _, h := range authHeaders { - if strings.HasPrefix(h, "BASIC") { - er.authType = authTypeBasic - } else if strings.HasPrefix(h, "NTLM") { - er.authType = authTypeNTLM - break // NTLM is the best we could do + if er.authType == authTypeUnknown { + // Find authentication scheme. + resp, err := http.DefaultClient.Get(r.URL.String()) + if err == nil && resp.StatusCode == http.StatusUnauthorized { + // This is a good time to find out what the server prefers. + authHeaders := resp.Header["Www-Authenticate"] + if authHeaders != nil { + for _, h := range authHeaders { + if strings.HasPrefix(h, "BASIC") { + er.authType = authTypeBasic + } 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 { // We need to replace the delegator. er.delegate = &httpntlm.NtlmTransport{ @@ -96,13 +92,15 @@ func (er EWSRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { Password: er.password, } } - er.initMutex.Unlock() - return er.RoundTrip(r) } } - 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 {