generated from fluffy-bunny/fluffycore-grpc-starterkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_endpoint_authorization_code.go
191 lines (176 loc) · 6.72 KB
/
token_endpoint_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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package token_endpoint
import (
"fmt"
"net/http"
"regexp"
contracts_tokenservice "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/contracts/tokenservice"
models "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/models"
proto_oidc_flows "github.com/fluffy-bunny/fluffycore-rage-identity/proto/oidc/flows"
proto_oidc_models "github.com/fluffy-bunny/fluffycore-rage-identity/proto/oidc/models"
fluffycore_services_claims "github.com/fluffy-bunny/fluffycore/services/claims"
fluffycore_utils "github.com/fluffy-bunny/fluffycore/utils"
oauth2 "github.com/go-oauth2/oauth2/v4"
status "github.com/gogo/status"
echo "github.com/labstack/echo/v4"
zerolog "github.com/rs/zerolog"
codes "google.golang.org/grpc/codes"
)
type TokenEndpointAuthorizationCodeRequest struct {
GrantType string `param:"grant_type" query:"grant_type" form:"grant_type" json:"grant_type" xml:"grant_type"`
Code string `param:"code" query:"code" form:"code" json:"code" xml:"code"`
CodeVerifier string `param:"code_verifier" query:"code_verifier" form:"code_verifier" json:"code_verifier" xml:"code_verifier"`
RedirectURI string `param:"redirect_uri" query:"redirect_uri" form:"redirect_uri" json:"redirect_uri" xml:"redirect_uri"`
}
type TokenEndpointAuthorizationCodeResponse struct {
AccessToken string `json:"access_token,omitempty"`
TokenType string `json:"token_type,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
}
func (s *service) validateTokenEndpointAuthorizationCodeRequest(req *TokenEndpointAuthorizationCodeRequest) error {
if req.GrantType != string(oauth2.AuthorizationCode) {
return status.Error(codes.InvalidArgument, "invalid_request - grant_type must be authorization_code")
}
if fluffycore_utils.IsEmptyOrNil(req.Code) {
return status.Error(codes.InvalidArgument, "invalid_request - code is empty")
}
if req.RedirectURI == "" {
return status.Error(codes.InvalidArgument, "invalid_request - redirect_uri is empty")
}
return nil
}
func extractIdpSlug(template string) (string, error) {
// Define the regular expression pattern
pattern := `^urn:rage:idp:([^:]+)?$`
// Compile the regular expression
re, err := regexp.Compile(pattern)
if err != nil {
return "", err
}
// Match the template against the regular expression
match := re.FindStringSubmatch(template)
if match == nil {
return "", fmt.Errorf("invalid template format")
}
return match[1], nil
}
func (s *service) handleAuthorizationCode(c echo.Context) error {
r := c.Request()
ctx := r.Context()
log := zerolog.Ctx(ctx).With().
Str("grant_type", string(oauth2.AuthorizationCode)).Logger()
clientI, err := s.scopedMemoryCache.Get("client")
if err != nil {
log.Error().Err(err).Msg("s.scopedMemoryCache.Get client")
return c.String(http.StatusBadRequest, err.Error())
}
client, ok := clientI.(*proto_oidc_models.Client)
if !ok {
log.Error().Msg("clientI.(*proto_oidc_models.Client)")
return c.String(http.StatusBadRequest, "clientI.(*proto_oidc_models.Client)")
}
allowedGrantType := false
// is this client allowed to use the authorization_code grant type?
for _, gt := range client.AllowedGrantTypes {
allowedGrantType = (gt == string(oauth2.AuthorizationCode))
if allowedGrantType {
break
}
}
if !allowedGrantType {
log.Error().Msg("allowedGrantType")
return c.String(http.StatusUnauthorized, "allowedGrantType")
}
req := &TokenEndpointAuthorizationCodeRequest{}
if err := c.Bind(req); err != nil {
log.Error().Err(err).Msg("Bind")
return err
}
err = s.validateTokenEndpointAuthorizationCodeRequest(req)
if err != nil {
log.Error().Err(err).Msg("validateTokenEndpointAuthorizationCodeRequest")
return c.String(http.StatusBadRequest, err.Error())
}
log.Debug().Interface("req", req).Msg("req")
getAuthorizationRequestStateResponse, err := s.authorizationRequestStateStore.GetAuthorizationRequestState(ctx,
&proto_oidc_flows.GetAuthorizationRequestStateRequest{
State: req.Code,
})
if err != nil {
log.Warn().Err(err).Msg("GetAuthorizationRequestState")
return c.String(http.StatusBadRequest, err.Error())
}
authorizationFinal := getAuthorizationRequestStateResponse.AuthorizationRequestState
idClaims := fluffycore_services_claims.NewClaims()
//--REQUIRED--
idClaims.Set("aud", client.ClientId)
idClaims.Set("nonce", authorizationFinal.Request.Nonce)
idClaims.Set("sub", authorizationFinal.Identity.Subject)
//--REQUIRED FOR US --
idClaims.Set("client_id", client.ClientId)
idClaims.Set("email", authorizationFinal.Identity.Email)
idClaims.Set("email_verified", authorizationFinal.Identity.EmailVerified)
acrClaims := []string{
// always true
models.ACRIdpRoot,
}
if len(authorizationFinal.Identity.Acr) > 0 {
acrClaims = append(acrClaims, authorizationFinal.Identity.Acr...)
}
idpClaims := []string{}
for _, acrValue := range acrClaims {
idp, err := extractIdpSlug(acrValue)
if err != nil {
continue
}
idpClaims = append(idpClaims, idp)
}
amrClaims := authorizationFinal.Identity.Amr
idClaims.Set("acr", acrClaims)
idClaims.Set("amr", amrClaims)
idClaims.Set("idp", idpClaims)
//--OPTIONAL--
idToken, err := s.tokenService.MintToken(ctx, &contracts_tokenservice.MintTokenRequest{
Claims: idClaims,
DurationLifeTimeSeconds: 3600,
NotBeforeUnix: 0,
})
if err != nil {
log.Warn().Err(err).Msg("MintToken - idToken")
return c.String(http.StatusBadRequest, err.Error())
}
// this one is opaque and is only really good for calling user_info endpoint
accessTokenClaims := fluffycore_services_claims.NewClaims()
accessTokenClaims.Set("client_id", client.ClientId)
accessTokenClaims.Set("aud", client.ClientId)
accessTokenClaims.Set("sub", authorizationFinal.Identity.Subject)
accessToken, err := s.tokenService.MintToken(ctx, &contracts_tokenservice.MintTokenRequest{
Claims: accessTokenClaims,
DurationLifeTimeSeconds: 3600,
NotBeforeUnix: 0,
})
if err != nil {
log.Warn().Err(err).Msg("MintToken - accessToken")
return c.String(http.StatusBadRequest, err.Error())
}
response := &TokenEndpointAuthorizationCodeResponse{
AccessToken: accessToken.Token,
TokenType: "bearer",
ExpiresIn: 3600,
// TODO: Not something we want to support for an authentication only service.
//RefreshToken: "refresh_token",
IDToken: idToken.Token,
}
// return as json
defer func() {
log.Debug().Interface("response", response).Msg("response")
_, err := s.authorizationRequestStateStore.DeleteAuthorizationRequestState(ctx, &proto_oidc_flows.DeleteAuthorizationRequestStateRequest{
State: req.Code,
})
if err != nil {
log.Error().Err(err).Msg("DeleteAuthorizationRequestState")
}
}()
return c.JSONPretty(http.StatusOK, response, " ")
}