diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e662c78 --- /dev/null +++ b/LICENSE @@ -0,0 +1,5 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..acc63fe --- /dev/null +++ b/Readme.md @@ -0,0 +1,74 @@ +# appleLogin + +A tool for `Sign In with Apple` REST API written in `Golang` + +![go-report](https://goreportcard.com/badge/github.com/BillSJC/appleLogin) + +![logo here](logo.jpg) + +### What it dose? + +- Full support of JWT Authorization for Apple Developer +- Quick API to finish [Sign In with Apple REST API](https://developer.apple.com/documentation/signinwithapplerestapi) on Apple Document +- Tool to create callBackURL + +### Install: + +> go get github.com/BillSJC/appleLogin + +### Test: + +> go test + +### Quick Start + +```go +package main + +import ( + "fmt" + "github.com/BillSJC/appleLogin" +) + +func main(){ + a := appleLogin.InitAppleConfig("123ABC456D", //Team ID + "com.example.pkg", //Client ID (Service ID) + "https://www.example.com/callback", //Callback URL + "your Apple Key ID") //Key ID + + //import cert + err := a.LoadP8CertByFile("path to your p8 cert file") //path to cert file + //or you can load cert from a string + err = a.LoadP8CertByByte([]byte("set your cert string here")) + + if err != nil { + panic(err) + } + + //create callback URL + callbackURL := a.CreateCallbackURL("state here") + fmt.Println(callbackURL) + + // ... some code to get Apple`s AuthorizationCode + code := "xxxx" + token,err := a.GetAppleToken(code,3600) + if err != nil { + panic(err) + } + fmt.Println(token) + +} + +``` + +### Functions + +#### InitAppleConfig + +#### LoadP8CertByFile + +#### LoadP8CertByByte + +#### CreateCallbackURL + +#### GetAppleToken \ No newline at end of file diff --git a/appleLogin.go b/appleLogin.go new file mode 100644 index 0000000..86d026c --- /dev/null +++ b/appleLogin.go @@ -0,0 +1,124 @@ +package appleLogin + +import ( + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "github.com/dgrijalva/jwt-go" + "github.com/parnurzeal/gorequest" + "io/ioutil" + "net/url" + "time" +) + +// AppleConfig Main struct of the package +type AppleConfig struct { + TeamID string //Your Apple Team ID + ClientID string //Your Service which enable sign-in-with-apple service + RedirectURI string //Your RedirectURI config in apple website + KeyID string //Your Secret Key ID + AESCert interface{} //Your Secret Key Created By X509 package +} + +// AppleAuthToken main response of apple REST-API +type AppleAuthToken struct { + AccessToken string `json:"access_token"` //AccessToken + ExpiresIn int64 `json:"expires_in"` //Expires in + IDToken string `json:"id_token"` //ID token + RefreshToken string `json:"refresh_token"` //RF token + TokenType string `json:"token_type"` //Token Type +} + +const AppleAuthURL = "https://appleid.apple.com/auth/token" //the auth URL of apple +const AppleGrantType = "authorization_code" //the grant type of apple auth + +//LoadP8CertByByte use x509.ParsePKCS8PrivateKey to Parse cert file +func (a *AppleConfig) LoadP8CertByByte(str []byte) (err error) { + block, _ := pem.Decode([]byte(str)) + cert, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return + } + a.AESCert = cert + return nil +} + +//LoadP8CertByFile load file and Parse it +func (a *AppleConfig) LoadP8CertByFile(path string) (err error) { + b, err := ioutil.ReadFile(path) + if err != nil { + return + } + return a.LoadP8CertByByte([]byte(b)) +} + +//InitAppleConfig init a new Client of this pkg +func InitAppleConfig(teamID string, clientID string, redirectURI string, keyID string) *AppleConfig { + return &AppleConfig{ + teamID, + clientID, + redirectURI, + keyID, + nil, + } +} + +//CreateCallbackURL create a callback URL for frontend +func (a *AppleConfig) CreateCallbackURL(state string) string { + u := url.Values{} + u.Add("response_type", "code") + u.Add("redirect_uri", a.RedirectURI) + u.Add("client_id", a.ClientID) + u.Add("state", state) + u.Add("scope", "name email") + return "https://appleid.apple.com/auth/authorize?" + u.Encode() +} + +//input your code and expire-time to get AccessToken of apple +func (a *AppleConfig) GetAppleToken(code string, expireTime int64) (*AppleAuthToken, error) { + //test cert + if a.AESCert == nil { + return nil, errors.New("missing cert") + } + //set jwt + token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ + "iss": a.TeamID, + "iat": time.Now().Unix(), + "exp": time.Now().Unix() + expireTime, + "aud": "https://appleid.apple.com", + "sub": a.ClientID, + }) + //set JWT header + token.Header = map[string]interface{}{ + "kid": a.KeyID, + "alg": "ES256", + } + //make JWT sign + tokenString, _ := token.SignedString(a.AESCert) + v := url.Values{} + v.Set("client_id", a.ClientID) + v.Set("client_secret", tokenString) + v.Set("code", code) + v.Set("grant_type", AppleGrantType) + v.Set("redirect_uri", a.RedirectURI) + fmt.Println(tokenString) + vs := v.Encode() + //send request + resp, body, err2 := gorequest.New().Post("https://appleid.apple.com/auth/token").Type("urlencoded").Send(vs).End() + if err2 != nil { + return nil, fmt.Errorf(fmt.Sprint(err2)) + } + //check response + if resp.StatusCode != 200 { + fmt.Println(body) + panic(errors.New("post failed : resp code is not 200")) + } + t := new(AppleAuthToken) + err := json.Unmarshal([]byte(body), t) + if err != nil { + return nil, err + } + return t, nil +} diff --git a/appleLogin_test.go b/appleLogin_test.go new file mode 100644 index 0000000..dd920ab --- /dev/null +++ b/appleLogin_test.go @@ -0,0 +1,20 @@ +package appleLogin + +import "testing" + +//a random p8 cert to go test +const certStr = `-----BEGIN PRIVATE KEY----- +MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgusZ/Y029MmQ4mXWn +fnzXUMI/DgtJIJdvG3cZtOsL3pmgCgYIKoZIzj0DAQehRANCAASQloEXsIF31S59 +n5/2YdbDaijlx2eIyIfkv7tre3GxgG8NILwvNCrg6L9Tm9JkVjsLucwXcQ+ezINf +YJBJn/t2 +-----END PRIVATE KEY-----` + +func TestAppleConfig_LoadP8CertByByte(t *testing.T) { + + a := InitAppleConfig("", "", "", "") + err := a.LoadP8CertByByte([]byte(certStr)) + if err != nil { + t.Fatal(err) + } +} diff --git a/cert.p8 b/cert.p8 new file mode 100644 index 0000000..2fd1780 --- /dev/null +++ b/cert.p8 @@ -0,0 +1,6 @@ +-----BEGIN PRIVATE KEY----- +MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgusZ/Y029MmQ4mXWn +fnzXUMI/DgtJIJdvG3cZtOsL3pmgCgYIKoZIzj0DAQehRANCAASQloEXsIF31S59 +n5/2YdbDaijlx2eIyIfkv7tre3GxgG8NILwvNCrg6L9Tm9JkVjsLucwXcQ+ezINf +YJBJn/t2 +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..171378f --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module github.com/BillSJC/appleLogin + +go 1.12 + +require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f // indirect + github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f // indirect + github.com/moul/http2curl v1.0.0 // indirect + github.com/parnurzeal/gorequest v0.2.15 + github.com/pkg/errors v0.8.1 + github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a // indirect + golang.org/x/net v0.0.0-20190603091049-60506f45cf65 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7c7f6f2 --- /dev/null +++ b/go.sum @@ -0,0 +1,28 @@ +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/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f h1:8GDPb0tCY8LQ+OJ3dbHb5sA6YZWXFORQYZx5sdsTlMs= +github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f h1:AUj1VoZUfhPhOPHULCQQDnGhRelpFWHMLhQVWDsS0v4= +github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/moul/http2curl v1.0.0 h1:dRMWoAtb+ePxMlLkrCbAqh4TlPHXvoGUSQ323/9Zahs= +github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/parnurzeal/gorequest v0.2.15 h1:oPjDCsF5IkD4gUk6vIgsxYNaSgvAnIh1EJeROn3HdJU= +github.com/parnurzeal/gorequest v0.2.15/go.mod h1:3Kh2QUMJoqw3icWAecsyzkpY7UzRfDhbRdTjtNwNiUE= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a h1:pa8hGb/2YqsZKovtsgrwcDH1RZhVbTKCjLp47XpqCDs= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= diff --git a/logo.jpg b/logo.jpg new file mode 100644 index 0000000..40dd943 Binary files /dev/null and b/logo.jpg differ