-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (72 loc) · 2.46 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/coreos/go-oidc"
gin_oidc "github.com/dakario/gin-oidc"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Initialize session cookie
store := cookie.NewStore([]byte("secret"))
router.Use(sessions.Sessions("mysession", store))
// gin OIDC middleware preparation
issuerUrl, _ := url.Parse("https://cloudsso.cisco.com")
clientUrl, _ := url.Parse("http://localhost:8080/")
logoutUrl, _ := url.Parse("https://wwww.cisco.com/")
initParams := gin_oidc.InitParams{
Router: router,
ClientId: "",
ClientSecret: "",
Issuer: *issuerUrl,
ClientUrl: *clientUrl,
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
ErrorHandler: func(c *gin.Context) {
message := c.Errors.Last().Error()
c.IndentedJSON(http.StatusInternalServerError, message)
},
// Mind you, the gin-oidc code assumes the Idp _ALWAYS_ uses /protocol/openid-connect/logout to log out. This is not the case... .
// If your Idp doesn't, logging out will crash your code. Relevant code is at https://github.com/dakario/gin-oidc/blob/master/ginoidc.go#L75
// A refactor of that lib can fix that
PostLogoutUrl: *logoutUrl,
}
// To protect all endpoints
// router.Use(gin_oidc.Init(initParams))
// or... protect a individual endpoints
protectMiddleware := gin_oidc.Init(initParams)
router.GET("/secret", protectMiddleware, getProtected)
router.GET("/public", getPublic)
router.Run("0.0.0.0:8080")
}
func getPublic(ctx *gin.Context) {
username := getAuthenticatedUser(ctx)
if username == "" {
ctx.IndentedJSON(http.StatusOK, "Public Endpoint - no user logged in")
} else {
message := fmt.Sprintf("Public Endpoint - '%v' logged in", username)
ctx.IndentedJSON(http.StatusOK, message)
}
}
func getProtected(ctx *gin.Context) {
username := getAuthenticatedUser(ctx)
message := fmt.Sprintf("Protected Endpoint! User '%v' is authorized", username)
ctx.IndentedJSON(http.StatusOK, message)
}
func getAuthenticatedUser(ctx *gin.Context) string {
// Get the Claims we're returning
serverSession := sessions.Default(ctx)
claims := serverSession.Get("oidcClaims")
if claims != nil {
// claims is an Interface, cast it to []byte so we can JSON Unmarshal it
ss := map[string]string{}
json.Unmarshal([]byte(claims.(string)), &ss)
username := ss["sub"]
return username
}
return ""
}