init: 1.0.0

This commit is contained in:
Chang lue Tsen
2025-04-25 12:08:29 +09:00
commit 8addcc584b
1031 changed files with 76472 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apple 登录</title>
</head>
<body>
<div id="appleid-signin"></div>
<script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
<script type="text/javascript">
AppleID.auth.init({
clientId: 'web.jiashus.com', // 替换为你的服务 ID
scope: 'name email', // 可选,授权范围
redirectURI: 'https://test.ppanel.dev:8443/auth/apple/callback', // 替换为你的回调 URL
state: 'optional-csrf-token', // 可选
usePopup: false // 可选,是否使用弹窗方式
});
</script>
</body>
</html>
+76
View File
@@ -0,0 +1,76 @@
package apple
import (
"context"
"fmt"
"log"
"net/http"
"testing"
"github.com/gin-gonic/gin"
)
func TestAppleLogin(t *testing.T) {
t.Skipf("Skip TestAppleLogin test")
router := gin.Default()
router.LoadHTMLGlob("./*")
router.GET("/apple", func(c *gin.Context) {
c.HTML(http.StatusOK, "apple.html", gin.H{
"title": "Gin HTML Example",
"message": "Hello, Gin!",
})
})
router.POST("/auth/apple/callback", func(c *gin.Context) {
var req CallbackRequest
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
return
}
handleAppleCallBack(c, req)
})
_ = router.RunTLS(":8443", "certificate.crt", "private.key")
}
func handleAppleCallBack(ctx context.Context, request CallbackRequest) {
fmt.Printf("request: %+v\n", request)
// validate the token
client, err := New(Config{
TeamID: TeamID,
ClientID: ClientID,
KeyID: KeyID,
ClientSecret: ClientSecret,
RedirectURI: "https://test.ppanel.dev:8443/auth/apple/callback",
})
if err != nil {
fmt.Println("error creating apple client: " + err.Error())
return
}
resp, err := client.VerifyWebToken(ctx, request.Code)
if err != nil {
fmt.Println("error verifying token: " + err.Error())
return
}
if resp.Error != "" {
fmt.Printf("apple returned an error: %s - %s\n", resp.Error, resp.ErrorDescription)
return
}
// Get the unique user ID
unique, err := GetUniqueID(resp.IDToken)
if err != nil {
fmt.Println("error getting unique id: " + err.Error())
return
}
// Get the email
claim, err := GetClaims(resp.IDToken)
if err != nil {
fmt.Println("failed to get claims: " + err.Error())
return
}
email := (*claim)["email"]
emailVerified := (*claim)["email_verified"]
isPrivateEmail := (*claim)["is_private_email"]
// Voila!
log.Printf("\n unique: %s \n email: %s \n email_verified: %v \n is_private_email: %v", unique, email, emailVerified, isPrivateEmail)
}
+34
View File
@@ -0,0 +1,34 @@
package apple
import (
"fmt"
"net/http"
"time"
)
type Config struct {
TeamID string
ClientID string
KeyID string
ClientSecret string
RedirectURI string
}
// New creates a Client object with the default URLs and a default http client
func New(c Config) (*Client, error) {
fmt.Printf("config: %+v\n", c)
secret, err := GenerateClientSecret(c.ClientSecret, c.TeamID, c.ClientID, c.KeyID)
if err != nil {
fmt.Println("error generating secret: " + err.Error())
return nil, err
}
return &Client{
config: c,
validationURL: ValidationURL,
revokeURL: RevokeURL,
client: &http.Client{
Timeout: 5 * time.Second,
},
secret: secret,
}, nil
}
+134
View File
@@ -0,0 +1,134 @@
package apple
// WebValidationTokenRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
type WebValidationTokenRequest struct {
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
ClientID string
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
// It can also be generated using the GenerateClientSecret function provided in this package
ClientSecret string
// Code is the authorization code received from your applications user agent.
// The code is single use only and valid for five minutes.
Code string
// RedirectURI is the destination URI the code was originally sent to.
// Redirect URLs must be registered with Apple. You can register up to 10. Apple will throw an error with IP address
// URLs on the authorization screen, and will not let you add localhost in the developer portal.
RedirectURI string
}
// CallbackRequest Apple Callback Request
type CallbackRequest struct {
// Code is the authorization code received from your applications user agent.
// The code is single use only and valid for five minutes.
Code string `form:"code"`
IdToken string `form:"id_token"`
State string `form:"state"`
}
// AppValidationTokenRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
type AppValidationTokenRequest struct {
// ClientID is the package name of your app
ClientID string
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
// It can also be generated using the GenerateClientSecret function provided in this package
ClientSecret string
// The authorization code received in an authorization response sent to your app. The code is single-use only and valid for five minutes.
// Authorization code validation requests require this parameter.
Code string
}
// ValidationRefreshRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
type ValidationRefreshRequest struct {
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
ClientID string
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
// It can also be generated using the GenerateClientSecret function provided in this package
ClientSecret string
// RefreshToken is the refresh token given during a previous validation
RefreshToken string
}
// RevokeAccessTokenRequest is based off https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
type RevokeAccessTokenRequest struct {
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
ClientID string
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
// It can also be generated using the GenerateClientSecret function provided in this package
ClientSecret string
// AccessToken is the auth token given during a previous validation
AccessToken string
}
// RevokeRefreshTokenRequest is based off https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
type RevokeRefreshTokenRequest struct {
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
ClientID string
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
// It can also be generated using the GenerateClientSecret function provided in this package
ClientSecret string
// RefreshToken is the refresh token given during a previous validation
RefreshToken string
}
// ValidationResponse is based off of https://developer.apple.com/documentation/signinwithapplerestapi/tokenresponse
type ValidationResponse struct {
// (Reserved for future use) A token used to access allowed data. Currently, no data set has been defined for access.
AccessToken string `json:"access_token"`
// The type of access token. It will always be "bearer".
TokenType string `json:"token_type"`
// The amount of time, in seconds, before the access token expires. You can revalidate with the "RefreshToken"
ExpiresIn int `json:"expires_in"`
// The refresh token used to regenerate new access tokens. Store this token securely on your server.
// The refresh token isnt returned when validating an existing refresh token. Please refer to RefreshReponse below
RefreshToken string `json:"refresh_token"`
// A JSON Web Token that contains the users identity information.
IDToken string `json:"id_token"`
// Used to capture any error returned by the endpoint. Do not trust the response if this error is not nil
Error string `json:"error"`
// A more detailed precision about the current error.
ErrorDescription string `json:"error_description"`
}
// RefreshResponse is a subset of ValidationResponse returned by Apple
type RefreshResponse struct {
// (Reserved for future use) A token used to access allowed data. Currently, no data set has been defined for access.
AccessToken string `json:"access_token"`
// The type of access token. It will always be "bearer".
TokenType string `json:"token_type"`
// The amount of time, in seconds, before the access token expires. You can revalidate with this token
ExpiresIn int `json:"expires_in"`
// Used to capture any error returned by the endpoint. Do not trust the response if this error is not nil
Error string `json:"error"`
// A more detailed precision about the current error.
ErrorDescription string `json:"error_description"`
}
// RevokeResponse is based of https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
type RevokeResponse struct {
// Used to capture any error returned by the endpoint
Error string `json:"error"`
// A more detailed precision about the current error.
ErrorDescription string `json:"error_description"`
}
+53
View File
@@ -0,0 +1,53 @@
package apple
import (
"crypto/x509"
"encoding/pem"
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
)
/*
GenerateClientSecret generates the client secret used to make requests to the validation server.
The secret expires after 6 months
signingKey - Private key from Apple obtained by going to the keys section of the developer section
teamID - Your 10-character Team ID
clientID - Your Services ID, e.g. com.aaronparecki.services
keyID - Find the 10-char Key ID value from the portal
*/
func GenerateClientSecret(signingKey, teamID, clientID, keyID string) (string, error) {
block, _ := pem.Decode([]byte(signingKey))
if block == nil {
return "", errors.New("empty block after decoding")
}
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return "", err
}
// Create the Claims
now := time.Now()
claims := &jwt.RegisteredClaims{
Issuer: teamID,
IssuedAt: &jwt.NumericDate{
Time: now,
},
ExpiresAt: &jwt.NumericDate{
Time: now.Add(time.Hour*24*180 - time.Second), // 180 days
},
Audience: jwt.ClaimStrings{
"https://appleid.apple.com",
},
Subject: clientID,
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["alg"] = "ES256"
token.Header["kid"] = keyID
return token.SignedString(privateKey)
}
+200
View File
@@ -0,0 +1,200 @@
package apple
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
// ValidationURL is the endpoint for verifying tokens
ValidationURL string = "https://appleid.apple.com/auth/token"
// RevokeURL is the endpoint for revoking tokens
RevokeURL string = "https://appleid.apple.com/auth/revoke"
// ContentType is the one expected by Apple
ContentType string = "application/x-www-form-urlencoded"
// UserAgent is required by Apple or the request will fail
UserAgent string = "go-signin-with-apple"
// AcceptHeader is the content that we are willing to accept
AcceptHeader string = "application/json"
)
// ValidationClient is an interface to call the validation API
type ValidationClient interface {
VerifyWebToken(ctx context.Context, reqBody WebValidationTokenRequest, result interface{}) error
VerifyAppToken(ctx context.Context, reqBody AppValidationTokenRequest, result interface{}) error
VerifyRefreshToken(ctx context.Context, reqBody ValidationRefreshRequest, result interface{}) error
RevokeAccessToken(ctx context.Context, reqBody RevokeAccessTokenRequest, result interface{}) error
RevokeRefreshToken(ctx context.Context, reqBody RevokeRefreshTokenRequest, result interface{}) error
}
// Client implements ValidationClient
type Client struct {
config Config
validationURL string
revokeURL string
secret string
client *http.Client
}
// ClientOptions is a struct to hold the options for the client
type ClientOptions struct {
validationURL string
revokeURL string
//nolint:unused
secret string
client *http.Client
}
// NewWithURL creates a Client object with a custom URL provided
//
// Deprecated: This function is deprecated and will be removed in a future version. Use NewWithOptions instead.
func NewWithURL(validationURL string, revokeURL string) *Client {
return NewWithOptions(ClientOptions{
validationURL: validationURL,
revokeURL: revokeURL,
})
}
// NewWithOptions creates a Client object with custom options. It will default to the standard options if not provided
func NewWithOptions(options ClientOptions) *Client {
if options.client == nil {
options.client = &http.Client{
Timeout: 5 * time.Second,
}
}
if options.validationURL == "" {
options.validationURL = ValidationURL
}
if options.revokeURL == "" {
options.revokeURL = RevokeURL
}
client := &Client{
validationURL: options.validationURL,
revokeURL: options.revokeURL,
client: options.client,
}
return client
}
// VerifyWebToken sends the WebValidationTokenRequest and gets validation result
func (c *Client) VerifyWebToken(ctx context.Context, code string) (ValidationResponse, error) {
data := url.Values{
"client_id": {c.config.ClientID},
"client_secret": {c.secret},
"code": {code},
"redirect_uri": {c.config.RedirectURI},
"grant_type": {"authorization_code"},
}
var resp ValidationResponse
err := doRequest(ctx, c.client, &resp, c.validationURL, data)
return resp, err
}
// VerifyAppToken sends the AppValidationTokenRequest and gets validation result
func (c *Client) VerifyAppToken(ctx context.Context, reqBody AppValidationTokenRequest, result interface{}) error {
data := url.Values{
"client_id": {reqBody.ClientID},
"client_secret": {reqBody.ClientSecret},
"code": {reqBody.Code},
"grant_type": {"authorization_code"},
}
return doRequest(ctx, c.client, &result, c.validationURL, data)
}
// VerifyRefreshToken sends the WebValidationTokenRequest and gets validation result
func (c *Client) VerifyRefreshToken(ctx context.Context, reqBody ValidationRefreshRequest, result interface{}) error {
data := url.Values{
"client_id": {reqBody.ClientID},
"client_secret": {reqBody.ClientSecret},
"refresh_token": {reqBody.RefreshToken},
"grant_type": {"refresh_token"},
}
return doRequest(ctx, c.client, &result, c.validationURL, data)
}
// RevokeRefreshToken revokes the Refresh Token and gets the revoke result
func (c *Client) RevokeRefreshToken(ctx context.Context, token string, result interface{}) error {
data := url.Values{
"client_id": {c.config.ClientID},
"client_secret": {c.secret},
"token": {token},
"token_type_hint": {"refresh_token"},
}
return doRequest(ctx, c.client, result, c.revokeURL, data)
}
// RevokeAccessToken revokes the Access Token and gets the revoke result
func (c *Client) RevokeAccessToken(ctx context.Context, token string, result interface{}) error {
data := url.Values{
"client_id": {c.config.ClientID},
"client_secret": {c.secret},
"token": {token},
"token_type_hint": {"access_token"},
}
log.Printf("revoke access token: %v", data)
return doRequest(ctx, c.client, &result, c.revokeURL, data)
}
// GetUniqueID decodes the id_token response and returns the unique subject ID to identify the user
func GetUniqueID(idToken string) (string, error) {
token, _, err := new(jwt.Parser).ParseUnverified(idToken, jwt.MapClaims{})
if err != nil {
return "", err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return "", fmt.Errorf("invalid token claims")
}
return fmt.Sprintf("%v", claims["sub"]), nil
}
// GetClaims decodes the id_token response and returns the JWT claims to identify the user
func GetClaims(idToken string) (*jwt.MapClaims, error) {
token, _, err := new(jwt.Parser).ParseUnverified(idToken, jwt.MapClaims{})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("invalid token claims")
}
return &claims, nil
}
func doRequest(ctx context.Context, client *http.Client, result interface{}, url string, data url.Values) error {
req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(data.Encode()))
if err != nil {
return err
}
req.Header.Add("content-type", ContentType)
req.Header.Add("accept", AcceptHeader)
req.Header.Add("user-agent", UserAgent) // apple requires a user agent
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("error response from apple: %s", res.Status)
}
return json.NewDecoder(res.Body).Decode(result)
}