/
oauth2_authorization_code.go
73 lines (61 loc) · 2.19 KB
/
oauth2_authorization_code.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
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/ECNU/Open-OAuth2Playground/g"
"github.com/ECNU/Open-OAuth2Playground/models"
"github.com/gin-gonic/gin"
)
type ExchangeTokenByCodeRequest struct {
Code string `json:"code"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Scope string `json:"scope"`
RedirectURI string `json:"redirect_uri"`
}
type RefreshTokenRequest struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RefreshToken string `json:"refresh_token"`
}
func exchangeTokenByCode(c *gin.Context) {
request := ExchangeTokenByCodeRequest{}
if err := c.Bind(&request); err != nil {
c.JSON(http.StatusOK, handleError(err.Error()))
return
}
method := "POST"
apiAddr := g.Config().Endpoints.Token
grant_type := "authorization_code"
body := fmt.Sprintf("code=%s&redirect_uri=%s&client_id=%s&client_secret=%s&scope=%s&grant_type=%s", request.Code, request.RedirectURI, request.ClientID, request.ClientSecret, request.Scope, grant_type)
header := make(map[string]string)
header["Content-Type"] = "application/x-www-form-urlencoded"
header["Content-Length"] = strconv.Itoa(len(body))
res, err := models.HandleRequest(method, apiAddr, g.UserAgent, body, g.Config().Timeout, header)
if err != nil {
c.JSON(http.StatusOK, handleError(err.Error()))
return
}
c.JSON(http.StatusOK, handleSuccess(res))
}
func refreshToken(c *gin.Context) {
request := RefreshTokenRequest{}
if err := c.Bind(&request); err != nil {
c.JSON(http.StatusOK, handleError(err.Error()))
return
}
method := "POST"
apiAddr := g.Config().Endpoints.Token
grant_type := "refresh_token"
body := fmt.Sprintf("grant_type=%s&client_id=%s&client_secret=%s&refresh_token=%s", grant_type, request.ClientID, request.ClientSecret, request.RefreshToken)
header := make(map[string]string)
header["Content-Type"] = "application/x-www-form-urlencoded"
header["Content-Length"] = strconv.Itoa(len(body))
res, err := models.HandleRequest(method, apiAddr, g.UserAgent, body, g.Config().Timeout, header)
if err != nil {
c.JSON(http.StatusOK, handleError(err.Error()))
return
}
c.JSON(http.StatusOK, handleSuccess(res))
}