Commit c04cf67d authored by Mathias Engelbrecht Pilegård's avatar Mathias Engelbrecht Pilegård
Browse files

added okta-resource server example to project

parent a49a34cc
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
# misc # misc
.DS_Store .DS_Store
.env
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local
......
CLIENT_ID=dev-91882654.okta.com
SPA_CLIENT_ID=0oa1f4zfeiiZPB6DF5d7
ISSUER=https://dev-91882654.okta.com/oauth2/default
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
verifier "github.com/okta/okta-jwt-verifier-golang"
oktaUtils "github.com/okta/samples-golang/resource-server/utils"
)
func main() {
oktaUtils.ParseEnvironment()
http.HandleFunc("/", HomeHandler)
http.HandleFunc("/api/messages", ApiMessagesHandler)
log.Print("server starting at localhost:3030 ... ")
err := http.ListenAndServe("localhost:3030", nil)
if err != nil {
log.Printf("the HTTP server failed to start: %s", err)
os.Exit(1)
}
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Resource server started, please start front-end application")
}
func ApiMessagesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type, authorization")
w.Header().Add("Access-Control-Allow-Methods", "GET, POST,OPTIONS")
if r.Method == "OPTIONS" {
return
}
if !isAuthenticated(r) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("401 - You are not authorized for this request"))
return
}
m1 := Message{1522272240, "I am a robot."}
m2 := Message{1522268640, "Hello, World!"}
allMessages := []Message{}
allMessages = append(allMessages, m1)
allMessages = append(allMessages, m2)
mess := Messages{
allMessages,
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(mess)
}
type Message struct {
Date float64 `json:"date"`
Text string `json:"text"`
}
type Messages struct {
MessageList []Message `json:"messages"`
}
func isAuthenticated(r *http.Request) bool {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return false
}
tokenParts := strings.Split(authHeader, "Bearer ")
bearerToken := tokenParts[1]
tv := map[string]string{}
tv["aud"] = "api://default"
tv["cid"] = os.Getenv("SPA_CLIENT_ID")
jv := verifier.JwtVerifier{
Issuer: os.Getenv("ISSUER"),
ClaimsToValidate: tv,
}
_, err := jv.New().VerifyAccessToken(bearerToken)
if err != nil {
return false
}
return true
}
package utils
import (
"crypto/rand"
"encoding/base64"
"fmt"
)
func GenerateNonce() (string, error) {
nonceBytes := make([]byte, 32)
_, err := rand.Read(nonceBytes)
if err != nil {
return "", fmt.Errorf("could not generate nonce")
}
return base64.URLEncoding.EncodeToString(nonceBytes), nil
}
package utils
import (
"bufio"
"log"
"os"
"strings"
)
func ParseEnvironment() {
// useGlobalEnv := true
if _, err := os.Stat(".env"); os.IsNotExist(err) {
log.Printf("Environment Variable file (.env) is not present. Relying on Global Environment Variables")
// useGlobalEnv = false
}
setEnvVariable("CLIENT_ID", os.Getenv("CLIENT_ID"))
setEnvVariable("SPA_CLIENT_ID", os.Getenv("SPA_CLIENT_ID"))
setEnvVariable("ISSUER", os.Getenv("ISSUER"))
if os.Getenv("CLIENT_ID") == "" {
log.Printf("Could not resolve a CLIENT_ID environment variable.")
os.Exit(1)
}
if os.Getenv("SPA_CLIENT_ID") == "" {
log.Printf("Could not resolve a SPA_CLIENT_ID environment variable.")
os.Exit(1)
}
if os.Getenv("ISSUER") == "" {
log.Printf("Could not resolve a ISSUER environment variable.")
os.Exit(1)
}
}
func setEnvVariable(env string, current string) {
if current != "" {
return
}
file, _ := os.Open(".env")
defer file.Close()
lookInFile := bufio.NewScanner(file)
lookInFile.Split(bufio.ScanLines)
for lookInFile.Scan() {
parts := strings.Split(lookInFile.Text(), "=")
key, value := parts[0], parts[1]
if key == env {
os.Setenv(key, value)
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment