github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_request_auth.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"fmt"
    11  	"net/http"
    12  	"strings"
    13  
    14  	"github.com/wangyougui/gf/v2/encoding/gbase64"
    15  )
    16  
    17  // BasicAuth enables the http basic authentication feature with a given passport and password
    18  // and asks client for authentication. It returns true if authentication success, else returns
    19  // false if failure.
    20  func (r *Request) BasicAuth(user, pass string, tips ...string) bool {
    21  	auth := r.Header.Get("Authorization")
    22  	if auth == "" {
    23  		r.setBasicAuth(tips...)
    24  		return false
    25  	}
    26  	authArray := strings.SplitN(auth, " ", 2)
    27  	if len(authArray) != 2 {
    28  		r.Response.WriteStatus(http.StatusForbidden)
    29  		return false
    30  	}
    31  	switch authArray[0] {
    32  	case "Basic":
    33  		authBytes, err := gbase64.DecodeString(authArray[1])
    34  		if err != nil {
    35  			r.Response.WriteStatus(http.StatusForbidden, err.Error())
    36  			return false
    37  		}
    38  		authArray := strings.SplitN(string(authBytes), ":", 2)
    39  		if len(authArray) != 2 {
    40  			r.Response.WriteStatus(http.StatusForbidden)
    41  			return false
    42  		}
    43  		if authArray[0] != user || authArray[1] != pass {
    44  			r.setBasicAuth(tips...)
    45  			return false
    46  		}
    47  		return true
    48  
    49  	default:
    50  		r.Response.WriteStatus(http.StatusForbidden)
    51  		return false
    52  	}
    53  }
    54  
    55  // setBasicAuth sets the http basic authentication tips.
    56  func (r *Request) setBasicAuth(tips ...string) {
    57  	realm := ""
    58  	if len(tips) > 0 && tips[0] != "" {
    59  		realm = tips[0]
    60  	} else {
    61  		realm = "Need Login"
    62  	}
    63  	r.Response.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
    64  	r.Response.WriteHeader(http.StatusUnauthorized)
    65  }