Skip to content

Commit 519100f

Browse files
authored
Merge pull request grafana#6217 from ericpp/oauth_add_state_param
Added a state parameter for all OAuth requests
2 parents b0d154d + 81443bf commit 519100f

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pkg/api/login_oauth.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package api
33
import (
44
"errors"
55
"fmt"
6+
"crypto/rand"
7+
"encoding/base64"
68

79
"golang.org/x/oauth2"
810

@@ -14,6 +16,12 @@ import (
1416
"github.com/grafana/grafana/pkg/social"
1517
)
1618

19+
func GenStateString() string {
20+
rnd := make([]byte, 32)
21+
rand.Read(rnd)
22+
return base64.StdEncoding.EncodeToString(rnd)
23+
}
24+
1725
func OAuthLogin(ctx *middleware.Context) {
1826
if setting.OAuthService == nil {
1927
ctx.Handle(404, "login.OAuthLogin(oauth service not enabled)", nil)
@@ -29,7 +37,17 @@ func OAuthLogin(ctx *middleware.Context) {
2937

3038
code := ctx.Query("code")
3139
if code == "" {
32-
ctx.Redirect(connect.AuthCodeURL("", oauth2.AccessTypeOnline))
40+
state := GenStateString()
41+
ctx.Session.Set(middleware.SESS_KEY_OAUTH_STATE, state)
42+
ctx.Redirect(connect.AuthCodeURL(state, oauth2.AccessTypeOnline))
43+
return
44+
}
45+
46+
// verify state string
47+
savedState := ctx.Session.Get(middleware.SESS_KEY_OAUTH_STATE).(string)
48+
queryState := ctx.Query("state")
49+
if savedState != queryState {
50+
ctx.Handle(500, "login.OAuthLogin(state mismatch)", nil)
3351
return
3452
}
3553

pkg/middleware/session.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313

1414
const (
1515
SESS_KEY_USERID = "uid"
16+
SESS_KEY_OAUTH_STATE = "state"
1617
)
1718

1819
var sessionManager *session.Manager

0 commit comments

Comments
 (0)