github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_request_auth.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"fmt"
    11  	"net/http"
    12  	"strings"
    13  
    14  	"github.com/zhongdalu/gf/g/encoding/gbase64"
    15  )
    16  
    17  // 设置Basic Auth校验提示
    18  func (r *Request) setBasicAuth(tips ...string) {
    19  	realm := ""
    20  	if len(tips) > 0 && tips[0] != "" {
    21  		realm = tips[0]
    22  	} else {
    23  		realm = "Need Login"
    24  	}
    25  	r.Response.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
    26  	r.Response.WriteHeader(http.StatusUnauthorized)
    27  }
    28  
    29  // 设置HTTP基础账号密码认证,如果用户没有提交账号密码,那么提示用户输出信息。
    30  // 验证成功之后返回true,否则返回false。
    31  func (r *Request) BasicAuth(user, pass string, tips ...string) bool {
    32  	auth := r.Header.Get("Authorization")
    33  	if auth == "" {
    34  		r.setBasicAuth(tips...)
    35  		return false
    36  	}
    37  	authArray := strings.SplitN(auth, " ", 2)
    38  	if len(authArray) != 2 {
    39  		r.Response.WriteStatus(http.StatusForbidden)
    40  		return false
    41  	}
    42  	switch authArray[0] {
    43  	case "Basic":
    44  		authBytes, err := gbase64.DecodeString(authArray[1])
    45  		if err != nil {
    46  			r.Response.WriteStatus(http.StatusForbidden, err.Error())
    47  			return false
    48  		}
    49  		authArray := strings.SplitN(string(authBytes), ":", 2)
    50  		if len(authArray) != 2 {
    51  			r.Response.WriteStatus(http.StatusForbidden)
    52  			return false
    53  		}
    54  		if authArray[0] != user || authArray[1] != pass {
    55  			r.setBasicAuth(tips...)
    56  			return false
    57  		}
    58  		return true
    59  
    60  	default:
    61  		r.Response.WriteStatus(http.StatusForbidden)
    62  		return false
    63  	}
    64  	return false
    65  }