github.com/TeaOSLab/EdgeNode@v1.3.8/internal/nodes/http_request_auth.go (about)

     1  // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package nodes
     4  
     5  import (
     6  	"bytes"
     7  	"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
     8  	"io"
     9  	"net/http"
    10  )
    11  
    12  // 执行认证
    13  func (this *HTTPRequest) doAuth() (shouldStop bool) {
    14  	if this.web.Auth == nil || !this.web.Auth.IsOn {
    15  		return
    16  	}
    17  
    18  	for _, ref := range this.web.Auth.PolicyRefs {
    19  		if !ref.IsOn || ref.AuthPolicy == nil || !ref.AuthPolicy.IsOn {
    20  			continue
    21  		}
    22  		if !ref.AuthPolicy.MatchRequest(this.RawReq) {
    23  			continue
    24  		}
    25  		ok, newURI, uriChanged, err := ref.AuthPolicy.Filter(this.RawReq, func(subReq *http.Request) (status int, err error) {
    26  			subReq.TLS = this.RawReq.TLS
    27  			subReq.RemoteAddr = this.RawReq.RemoteAddr
    28  			subReq.Host = this.RawReq.Host
    29  			subReq.Proto = this.RawReq.Proto
    30  			subReq.ProtoMinor = this.RawReq.ProtoMinor
    31  			subReq.ProtoMajor = this.RawReq.ProtoMajor
    32  			subReq.Body = io.NopCloser(bytes.NewReader([]byte{}))
    33  			subReq.Header.Set("Referer", this.URL())
    34  			var writer = NewEmptyResponseWriter(this.writer)
    35  			this.doSubRequest(writer, subReq)
    36  			return writer.StatusCode(), nil
    37  		}, this.Format)
    38  		if err != nil {
    39  			this.write50x(err, http.StatusInternalServerError, "Failed to execute the AuthPolicy", "认证策略执行失败", false)
    40  			return
    41  		}
    42  		if ok {
    43  			if uriChanged {
    44  				this.uri = newURI
    45  			}
    46  			this.tags = append(this.tags, "auth:"+ref.AuthPolicy.Type)
    47  			return
    48  		} else {
    49  			// Basic Auth比较特殊
    50  			if ref.AuthPolicy.Type == serverconfigs.HTTPAuthTypeBasicAuth {
    51  				method, ok := ref.AuthPolicy.Method().(*serverconfigs.HTTPAuthBasicMethod)
    52  				if ok {
    53  					var headerValue = "Basic realm=\""
    54  					if len(method.Realm) > 0 {
    55  						headerValue += method.Realm
    56  					} else {
    57  						headerValue += this.ReqHost
    58  					}
    59  					headerValue += "\""
    60  					if len(method.Charset) > 0 {
    61  						headerValue += ", charset=\"" + method.Charset + "\""
    62  					}
    63  					this.writer.Header()["WWW-Authenticate"] = []string{headerValue}
    64  				}
    65  			}
    66  			this.writer.WriteHeader(http.StatusUnauthorized)
    67  			this.tags = append(this.tags, "auth:"+ref.AuthPolicy.Type)
    68  			return true
    69  		}
    70  	}
    71  	return
    72  }