Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return token #246

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ coverage.txt
*.swp
/example/client/client
/example/server/server
/example/secureYourMicroservices/db-oauth


29 changes: 29 additions & 0 deletions example/secureYourMicroservices/authorization/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module server

go 1.20

replace github.com/go-oauth2/oauth2/v4 => ../../../

require (
github.com/go-oauth2/oauth2/v4 v4.4.3
github.com/jackc/pgx/v4 v4.18.1
github.com/vgarvardt/go-oauth2-pg/v4 v4.4.3
github.com/vgarvardt/go-pg-adapter v1.0.0
)

require (
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.14.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.2 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgtype v1.14.0 // indirect
github.com/jackc/puddle v1.3.0 // indirect
github.com/jmoiron/sqlx v1.3.4 // indirect
github.com/vgarvardt/pgx-helpers/v4 v4.0.0-20200225100150-876aee3d1a22 // indirect
golang.org/x/crypto v0.6.0 // indirect
golang.org/x/text v0.7.0 // indirect
)
421 changes: 421 additions & 0 deletions example/secureYourMicroservices/authorization/go.sum

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
package handlers

import (
"fmt"
"github.com/go-oauth2/oauth2/v4/server"
"net/http"
"os"
"sync"
)

// List of the allowed services
var apiWhiteList = map[string]string{
"888888": "88888888",
}

// DBRepo is the db repo
type Authentication struct {
srv *server.Server
extStore map[string]interface{} // like a redis store
databaseUsers map[string]interface{} // use a db
// one mutex for 2 stores, ok for the demo
sync.RWMutex
}

// NewPostgresqlHandlers creates db repo for postgres
func NewAuthentication(srv *server.Server) Authentication {

return Authentication{
srv: srv,
extStore: make(map[string]interface{}),
databaseUsers: make(map[string]interface{}),
}
}

func (a Authentication) Authorize(w http.ResponseWriter, r *http.Request) {
if dumpvar {
dumpRequest(os.Stdout, "authorize", r)
}

err := a.srv.HandleAuthorizeRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

}

func (a Authentication) UserAuthorizeHandler(w http.ResponseWriter, r *http.Request) (userID string, err error) {
if dumpvar {
_ = dumpRequest(os.Stdout, "userAuthorizeHandler", r) // Ignore the error
}

clientID := r.Form.Get("client_id")

switch clientID {
case "222222":

a.RLock()
uid, ok := a.extStore[fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("email"))]
a.RUnlock()
if !ok {
if r.Form == nil {
r.ParseForm()
}

w.WriteHeader(http.StatusOK)
return
}

userID = uid.(string)

a.Lock()
delete(a.extStore, fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("email")))
a.Unlock()
return
case "888888":

a.RLock()
uid, ok := a.extStore[fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("client_id"))]
a.RUnlock()
if !ok {
if r.Form == nil {
r.ParseForm()
}

w.WriteHeader(http.StatusOK)
return
}

userID = uid.(string)

a.Lock()
delete(a.extStore, fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("client_id")))
a.Unlock()
return
default:
userID = ""
return
}
}

func (a Authentication) Token(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "token", r) // Ignore the error
}

err := a.srv.HandleTokenRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

// Endpoint specific for the APIs
func (a Authentication) ApiAuthHandler(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "apiAuthHandler", r) // Ignore the error
}

if r.Method == "POST" {

if r.Form == nil {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

// make sure the client's api is allow
_, ok := apiWhiteList[r.Form.Get("client_id")]
if ok {
// save user in a temporary store for the user to be reconized later on
a.Lock()
a.extStore[fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("client_id"))] = r.Form.Get("client_id")
a.Unlock()

a.Authorize(w, r)
return
} else {

http.Error(w, "Bad Request", http.StatusBadRequest)
return
}

}

http.Error(w, "Bad Request", http.StatusBadRequest)
}

func (a Authentication) SignupHandler(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "signup", r) // Ignore the error
}

if r.Method == "POST" {

if r.Form == nil {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

// some logic
if len(r.Form.Get("email")) < 1 && len(r.Form.Get("password")) < 1 {

http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
} else {
// Save the user in db(simplistic, for example)
a.Lock()
a.databaseUsers[fmt.Sprintf(r.Form.Get("email"))] = r.Form.Get("password")
a.Unlock()
}

// save user in a temporary store for the user to be reconized later on
a.Lock()
a.extStore[fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("email"))] = r.Form.Get("email")
a.Unlock()

a.Authorize(w, r)
return
}

http.Error(w, "Bad Request", http.StatusBadRequest)
}

func (a Authentication) LoginHandler(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "login", r) // Ignore the error
}

if r.Method == "POST" {

if r.Form == nil {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

if len(r.Form.Get("email")) < 1 && len(r.Form.Get("password")) < 1 {

http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
} else {
a.RLock()
password, ok := a.databaseUsers[fmt.Sprintf(r.Form.Get("email"))]
a.RUnlock()
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

if password != r.Form.Get("password") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

// save user in a temporary store for the user to be reconized later on
a.Lock()
a.extStore[fmt.Sprintf("LoggedInUserID-%v", r.Form.Get("email"))] = r.Form.Get("email")
a.Unlock()

}

a.Authorize(w, r)
return
}
http.Error(w, "Bad Request", http.StatusBadRequest)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package handlers

import (
"encoding/json"
"fmt"
"github.com/go-oauth2/oauth2/v4/server"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
)

var dumpvar bool

const (
authServerURL string = "http://localhost:9096"
)

type Handlers struct {
Permissions
Authentication
}

func NewHandlers(dv bool, srv *server.Server) *Handlers {
dumpvar = dv

perm := NewPermissions(srv)
auth := NewAuthentication(srv)

return &Handlers{
Permissions: perm,
Authentication: auth,
}

}

type Permissions struct {
srv *server.Server
}

func NewPermissions(srv *server.Server) Permissions {
return Permissions{
srv: srv,
}
}

// Endpoint to validate token and permission
func (p Permissions) ValidPermission(w http.ResponseWriter, r *http.Request) {
if dumpvar {
_ = dumpRequest(os.Stdout, "validPermission", r) // Ignore the error
}

// validate the token
token, err := p.srv.ValidationBearerToken(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

permission := r.URL.Query().Get("permission")

// validate the permission
switch permission {
case "read":
log.Println("In read permission")
if !strings.Contains(token.GetScope(), "read") && !strings.Contains(token.GetScope(), "all") {
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}

case "write":
log.Println("In write permission")
if !strings.Contains(token.GetScope(), "write") && !strings.Contains(token.GetScope(), "all") {
fmt.Println("do not have Write permission.")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}

case "all":
log.Println("In all permission")
if !strings.Contains(token.GetScope(), "all") {
fmt.Println("do not have All permission.")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}
default:
log.Println("In default permission")
http.Error(w, "Unauthorized", http.StatusBadRequest)
return
}

data := map[string]interface{}{
"expires_in": int64(token.GetAccessCreateAt().Add(token.GetAccessExpiresIn()).Sub(time.Now()).Seconds()),
"client_id": token.GetClientID(),
"user_id": token.GetUserID(),
"permission": token.GetScope(),
}
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(data)
}

func dumpRequest(writer io.Writer, header string, r *http.Request) error {
data, err := httputil.DumpRequest(r, true)
if err != nil {
return err
}
writer.Write([]byte("\n" + header + ": \n"))
writer.Write(data)
return nil
}
Loading