-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserinfo.go
128 lines (97 loc) · 2.37 KB
/
userinfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package userinfo
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
// Config the plugin configuration.
type Config struct {
UserinfoURL string `json:"userinfoURL,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
UserinfoURL: "foo",
}
}
// Example a plugin.
type UserInfo struct {
next http.Handler
name string
userinfoURL string
}
// New created a new plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &UserInfo{
next: next,
name: name,
userinfoURL: config.UserinfoURL,
}, nil
}
//curl -H "Authorization:Bearer vsN-QlQv2zi3SHPk6fOJuSA4_6h14OPiwkk1rcp-xoY.d4m1wrUnPhaXGeS9l-Z_muhdi0nKSpUiDp2dQnDQaYM" localhost:8082/test2
func (u *UserInfo) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
authorization := "no"
for header, value := range req.Header {
if header == "Authorization" {
authorization = value[0]
}
}
if authorization == "no" {
fmt.Fprintln(rw, "error_description:The request could not be authorized")
return
}
kv := strings.Split(authorization, " ")
if len(kv) != 2 || kv[0] != "Bearer" {
fmt.Fprintln(rw, "error_description:The request could not be authorized")
return
}
claims := get(u.userinfoURL, authorization)
if claims == "error" {
return
}
m := make(map[string]string)
err := json.Unmarshal([]byte(claims), &m)
if err != nil {
fmt.Fprintln(rw, "eeeerror_description:The request could not be authorized")
return
}
for k, v := range m {
if k == "sub" {
req.Header.Set("gridname", v)
}
}
u.next.ServeHTTP(rw, req)
}
// 发送GET请求
// url: 请求地址
// response: 请求返回的内容
func get(url string, token string) string {
// 超时时间:5秒
client := &http.Client{Timeout: 5 * time.Second}
request, err := http.NewRequest("GET", url, nil)
request.Header.Add("Authorization", token)
resp, err := client.Do(request)
if err != nil {
fmt.Println("error:userinfo!!!")
return "error"
}
defer resp.Body.Close()
var buffer [512]byte
result := bytes.NewBuffer(nil)
for {
n, err := resp.Body.Read(buffer[0:])
result.Write(buffer[0:n])
if err != nil && err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
return result.String()
}