forked from SAP/cloud-security-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
49 lines (41 loc) · 1.13 KB
/
middleware.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
// SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company and Cloud Security Client Go contributors
//
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"github.com/gorilla/handlers"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"github.com/sap/cloud-security-client-go/auth"
"github.com/sap/cloud-security-client-go/env"
)
// Main class for demonstration purposes.
func main() {
r := mux.NewRouter()
config, err := env.ParseIdentityConfig()
if err != nil {
panic(err)
}
authMiddleware := auth.NewMiddleware(config, auth.Options{})
r.Use(authMiddleware.AuthenticationHandler)
r.HandleFunc("/helloWorld", helloWorld).Methods(http.MethodGet)
address := ":8080"
server := &http.Server{
Addr: address,
ReadHeaderTimeout: 5 * time.Second,
Handler: handlers.LoggingHandler(os.Stdout, r),
}
log.Println("Starting server on address", address)
err = server.ListenAndServe()
if err != nil {
panic(err)
}
}
func helloWorld(w http.ResponseWriter, r *http.Request) {
user := auth.TokenFromCtx(r)
_, _ = fmt.Fprintf(w, "Hello world!\nYou're logged in as %s", user.Email())
}