ajout génération jwt local

This commit is contained in:
2021-01-19 07:21:15 +01:00
parent cf49499021
commit a148c7eb09
7 changed files with 84 additions and 7 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
auth.db auth.db
goauth20

2
go.mod
View File

@@ -3,7 +3,9 @@ module github.com/ldrogou/goauth20
go 1.15 go 1.15
require ( require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/mux v1.8.0 github.com/gorilla/mux v1.8.0
github.com/jmoiron/sqlx v1.2.0 github.com/jmoiron/sqlx v1.2.0
github.com/mattn/go-sqlite3 v1.14.6 github.com/mattn/go-sqlite3 v1.14.6
github.com/mitchellh/mapstructure v1.4.1
) )

5
go.sum
View File

@@ -1,3 +1,6 @@
github.com/dgrijalva/jwt-go v1.0.2 h1:KPldsxuKGsS2FPWsNeg9ZO18aCrGKujPoWXn2yo+KQM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
@@ -7,3 +10,5 @@ github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=

BIN
goauth20

Binary file not shown.

View File

@@ -9,6 +9,9 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
"time"
"github.com/dgrijalva/jwt-go"
) )
//File structure du fichier //File structure du fichier
@@ -32,6 +35,16 @@ type token struct {
refreshToken string `json:"refresh_token"` refreshToken string `json:"refresh_token"`
} }
// Create a struct that will be encoded to a JWT.
// We add jwt.StandardClaims as an embedded type, to provide fields like expiry time
type Claims struct {
Sub string `json:"sub"`
IDEntreprise string `json:"idEntreprise"`
RcaPartnerID string `json:"rcaPartnerId"`
Roles []string `json:"roles"`
jwt.StandardClaims
}
func (s *server) handleIndex() http.HandlerFunc { func (s *server) handleIndex() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "text/html") rw.Header().Set("Content-Type", "text/html")
@@ -51,14 +64,65 @@ func (s *server) handleIndex() http.HandlerFunc {
} }
} }
func (s *server) handleTest() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
fmt.Println("sub")
sub := r.FormValue("sub")
fmt.Printf("sub %v", sub)
idEntreprise := r.FormValue("id_entreprise")
fmt.Printf("idEntreprise %v", idEntreprise)
rcaPartnerID := r.FormValue("rcaPartnerId")
fmt.Printf("rcaPartnerID %v", rcaPartnerID)
var jwtKey = []byte(r.FormValue("secret"))
fmt.Printf("secret %v", jwtKey)
// Declare the expiration time of the token
// here, we have kept it as 5 minutes
expirationTime := time.Now().Add(5 * time.Hour)
roles := []string{"RCA_CLOUD_EXPERT_COMPTABLE",
"E_COLLECTE_BO_CREA",
"E_CREATION_CREA",
"E_QUESTIONNAIRE_CREA"}
// Create the JWT claims, which includes the username and expiry time
claims := &Claims{
Sub: sub,
IDEntreprise: idEntreprise,
RcaPartnerID: rcaPartnerID,
Roles: roles,
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: expirationTime.Unix(),
},
}
fmt.Printf("claims %v", claims)
// Declare the token with the algorithm used for signing, and the claims
tokenstr := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
fmt.Printf("token %v", tokenstr)
// Create the JWT string
tokenString, err := tokenstr.SignedString(jwtKey)
fmt.Printf("tokenString %v", tokenString)
if err != nil {
log.Printf("erreur %v", err)
// If there is an error in creating the JWT return an internal server error
rw.WriteHeader(http.StatusInternalServerError)
return
}
s.response(rw, r, tokenString, http.StatusOK)
}
}
func (s *server) handleRedirect() http.HandlerFunc { func (s *server) handleRedirect() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) {
codes, _ := r.URL.Query()["code"] codes, _ := r.URL.Query()["code"]
jsonStr := constJsonToken(codes[0]) jsonStr := constJsonToken(codes[0])
apiURL := "https://api.XXX.XXX.XXX/auth/v1/oauth2.0/accessToken" apiURL := "https://api.captation.beta.rca.fr/auth/v1/oauth2.0/accessToken"
data := url.Values{} data := url.Values{}
data.Set("client_id", jsonStr.clientID) data.Set("client_id", jsonStr.clientID)
data.Set("client_secret", jsonStr.clientSecret) data.Set("client_secret", jsonStr.clientSecret)
@@ -90,7 +154,7 @@ func (s *server) handleRedirect() http.HandlerFunc {
} }
defer resp.Body.Close() defer resp.Body.Close()
fmt.Println(t.(interface{}).(map[string]interface{})["access_token"]) tokenVal := t.(interface{}).(map[string]interface{})
if err != nil { if err != nil {
log.Printf("Cannot parse token body err=%v", err) log.Printf("Cannot parse token body err=%v", err)
@@ -98,7 +162,7 @@ func (s *server) handleRedirect() http.HandlerFunc {
return return
} }
s.response(rw, r, t, http.StatusOK) s.response(rw, r, tokenVal["access_token"], http.StatusOK)
} }
} }

View File

@@ -3,4 +3,6 @@ package main
func (s *server) routes() { func (s *server) routes() {
s.router.HandleFunc("/index", s.handleIndex()).Methods("GET") s.router.HandleFunc("/index", s.handleIndex()).Methods("GET")
s.router.HandleFunc("/oauth/redirect", s.handleRedirect()).Methods("GET") s.router.HandleFunc("/oauth/redirect", s.handleRedirect()).Methods("GET")
s.router.HandleFunc("/test", s.handleTest()).Methods("POST")
} }

View File

@@ -29,7 +29,11 @@
} }
function generateToken() { function generateToken() {
window.location = 'https://XXX.XXX.XXX/entreprise-partenaire/authorize?client_id=meg-test-interne&scope=user.read company.read accounting_firm.read sales&current_company=true&redirect_uri=http://localhost:8080/oauth/redirect' var form = document.getElementById("monform");
form.submit();
//window.location = 'https://captation.beta.rca.fr/entreprise-partenaire/authorize?client_id=meg-test-interne&scope=user.read company.read accounting_firm.read sales&current_company=true&redirect_uri=http://localhost:8080/oauth/redirect'
} }
function generate() { function generate() {
@@ -73,7 +77,7 @@
<body> <body>
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<form class="col s12"> <form class="col s12" id="monform" method="post" action="/test">
<div class="row"> <div class="row">
<div class="input-field col s12"> <div class="input-field col s12">
<i class="material-icons prefix">account_circle</i> <i class="material-icons prefix">account_circle</i>
@@ -118,7 +122,6 @@
</form> </form>
</div> </div>
</div> </div>
</body> </body>
</html> </html>