blob: 52d07e94f7b14f51964ed2aa49f5e7f9393582fa [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package auth
8
9import (
10 "context"
11
12 "github.com/mongodb/mongo-go-driver/x/network/description"
13 "github.com/mongodb/mongo-go-driver/x/network/wiremessage"
14)
15
16func newDefaultAuthenticator(cred *Cred) (Authenticator, error) {
17 return &DefaultAuthenticator{
18 Cred: cred,
19 }, nil
20}
21
22// DefaultAuthenticator uses SCRAM-SHA-1 or MONGODB-CR depending
23// on the server version.
24type DefaultAuthenticator struct {
25 Cred *Cred
26}
27
28// Auth authenticates the connection.
29func (a *DefaultAuthenticator) Auth(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter) error {
30 var actual Authenticator
31 var err error
32
33 switch chooseAuthMechanism(desc) {
34 case SCRAMSHA256:
35 actual, err = newScramSHA256Authenticator(a.Cred)
36 case SCRAMSHA1:
37 actual, err = newScramSHA1Authenticator(a.Cred)
38 default:
39 actual, err = newMongoDBCRAuthenticator(a.Cred)
40 }
41
42 if err != nil {
43 return newAuthError("error creating authenticator", err)
44 }
45
46 return actual.Auth(ctx, desc, rw)
47}
48
49// If a server provides a list of supported mechanisms, we choose
50// SCRAM-SHA-256 if it exists or else MUST use SCRAM-SHA-1.
51// Otherwise, we decide based on what is supported.
52func chooseAuthMechanism(desc description.Server) string {
53 if desc.SaslSupportedMechs != nil {
54 for _, v := range desc.SaslSupportedMechs {
55 if v == SCRAMSHA256 {
56 return v
57 }
58 }
59 return SCRAMSHA1
60 }
61
62 if err := description.ScramSHA1Supported(desc.WireVersion); err == nil {
63 return SCRAMSHA1
64 }
65
66 return MONGODBCR
67}