auth

package module
v0.0.0-...-e165d0c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2022 License: GPL-3.0 Imports: 13 Imported by: 0

README

Go client library for signing in with apple

For more information about apple sign in, please review apple doc.

Install

go get github.com/canopas/apple-sdk-go/auth

How to use?

  • TeamId : 10-char App Id prefix found in App identifiers section (Ex: AB65CD4321)

  • ClientId : ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID (Ex: com.example.me)

  • KeyId : This is the ID of the private key (Ex: FE12DC34BA)

  • Secret : This is the private key file (.p8). You can download it from apple portal


// Create new secret request with default client
req, err := auth.WithDefaultClient("team-id", "client-id", "key-id", "secret-key-file-path")

if err != nil {
	log.Fatal(err.Error())
}

// OR
// Create new secret request with custom client
client := &http.Client{
	Timeout: 10 * time.Second,
}

req, err := auth.WithCustomClient(client, "team-id", "client-id", "key-id", "secret-key-file-path")

if err != nil {
	log.Fatal(err.Error())
}

// To do authorization request validation with authorization code from mobile app
resp, err := req.ValidateCode(context.Background(), "auth-code") 

// OR
// To do authorization request validation with authorization code and redirect uri from web app
resp, err := req.ValidateCodeWithRedirectURI(context.Background(), "auth-code", "redirect-uri") 

// OR
// Refresh token validation request
resp, err := req.ValidateRefreshToken(context.Background(), "refresh-token") 

if err != nil {
	log.Fatal(err.Error())
}

// get user
user, err := resp.GetUser()

if err != nil {
	log.Fatal(err.Error())
}

log.Println(user)

// get user's uniqueId
id, err := resp.UniqueID()

if err != nil {
	log.Fatal(err.Error())
}

log.Println(id)

// get user email
email, err := resp.Email()

if err != nil {
	log.Fatal(err.Error())
}

log.Println(email)

// Get user status 
// The possible values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal)
userStatus, err := resp.RealUserStatus()

if err != nil {
	log.Fatal(err.Error())
}

log.Println(userStatus)

Documentation

Overview

secret generates the secret used for validation requests.

user retrive the information about validated apple user from idToken

validation handles the sign in token validations.

Index

Constants

View Source
const (
	VALIDATION_URL = "https://appleid.apple.com/auth/token"
	CONTENT_TYPE   = "application/x-www-form-urlencoded"
	USER_AGENT     = "apple-sdk-go"
	ACCEPT         = "application/json"
)
View Source
const (
	AUDIENCE = "https://appleid.apple.com"
)

Variables

View Source
var (

	// The request is malformed, typically because it’s missing a parameter,
	// contains an unsupported parameter, includes multiple credentials,
	// or uses more than one mechanism for authenticating the client.
	InvalidRequest    string = "invalid_request"
	InvalidRequestMsg string = "" /* 199-byte string literal not displayed */

	// The client authentication failed, typically due to a mismatched or invalid client identifier,
	// invalid client secret (expired token, malformed claims, or invalid signature), or mismatched or invalid redirect URI.
	InvalidClient    string = "invalid_client"
	InvalidClientMsg string = "" /* 211-byte string literal not displayed */

	// The authorization grant or refresh token is invalid,
	// typically due to a mismatched or invalid client identifier,
	// invalid code (expired or previously used authorization code),
	// or invalid refresh token.
	InvalidGrant    string = "invalid_grant"
	InvalidGrantMsg string = "" /* 200-byte string literal not displayed */

	// The client isn’t authorized to use this authorization grant type.
	UnauthorizedClient    string = "unauthorized_client"
	UnauthorizedClientMsg string = "The client is not authorized to use this authorization grant type."

	// The authenticated client isn’t authorized to use this grant type.
	UnsupportedGrantType    string = "unsupported_grant_type"
	UnsupportedGrantTypeMsg string = "The authenticated client is not authorized to use this grant type."

	// The requested scope is invalid.
	InvalidScope    string = "invalid_scope"
	InvalidScopeMsg string = "The requested scope is invalid."
)
View Source
var InvalidSecretFileMsg = "please specify secret key file path"

Functions

This section is empty.

Types

type Claims

type Claims struct{}

func (*Claims) GetClaims

func (c *Claims) GetClaims(idToken string) (jwt.MapClaims, error)

GetClaims decodes the idToken and returns the claims

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

type Request

type Request struct {
	// 10-char App Id prefix found in App identifiers section
	TeamID string

	//ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
	ClientID string

	// This is the ID of the private key
	KeyID string

	// This is the private key file (.p8). You can download it from apple portal
	ClientSecret []byte

	HttpClient httpClient
}

func WithCustomClient

func WithCustomClient(client httpClient, teamId, clientId, keyId, secretKeyPath string) (*Request, error)

Returns new secret request with given client

func WithDefaultClient

func WithDefaultClient(teamId, clientId, keyId, secretKeyPath string) (*Request, error)

Returns new secret request with default client

func (*Request) GenerateClientSecret

func (req *Request) GenerateClientSecret() (string, error)

GenerateClientSecret returns a secret used to validate server requests SecretRequest is required to generate secret. Method will throw error if data is empty or wrong.

func (*Request) NewRegisteredClaims

func (req *Request) NewRegisteredClaims() *jwt.RegisteredClaims

NewRegisteredClaims generates jwt claims from SecretRequest.

func (*Request) ValidateCode

func (req *Request) ValidateCode(ctx context.Context, code string) (*TokenResponse, error)

Validates request using the authorization code received in an authorization response sent to your app. Returns TokenResponse and error

func (*Request) ValidateCodeWithRedirectURI

func (req *Request) ValidateCodeWithRedirectURI(ctx context.Context, code string, redirectURI string) (*TokenResponse, error)

Validate request using destinatio URI provided in authorization request Returns TokenResponse and error

func (*Request) ValidateRefreshToken

func (req *Request) ValidateRefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)

Validates given refresh token Returns TokenResponse and error

type TokenResponse

type TokenResponse struct {

	// The refresh token used to regenerate new access tokens when validating an authorization code.
	// Store this token securely on your server.
	// The refresh token isn’t returned when validating an existing refresh token.
	RefreshToken string `json:"refresh_token"`

	// A token used to access allowed data,
	// such as generating and exchanging transfer identifiers during user migration
	AccessToken string `json:"access_token"`

	// The amount of time, in seconds, before the access token expires.
	ExpiresIn int `json:"expires_in"`

	// A JSON Web Token (JWT) that contains the user’s identity information.
	IDToken string `json:"id_token"`

	// The type of access token, which is always bearer.
	TokenType string `json:"token_type"`

	Claims claims
}

Response after validation process from apple

func (*TokenResponse) Email

func (resp *TokenResponse) Email() (string, error)

Email returns the user email

func (*TokenResponse) GetUser

func (resp *TokenResponse) GetUser() (*User, error)

GetUser will get claims, and returns the user using claims

func (*TokenResponse) RealUserStatus

func (resp *TokenResponse) RealUserStatus() (int, error)

RealUserStatus returns whether the user appears to be a real person. The possible values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal).

func (*TokenResponse) UniqueID

func (resp *TokenResponse) UniqueID() (string, error)

UniqueID returns the unique subject ID to identify the user

type User

type User struct {
	// The unique identifier for the user (sub).
	ID string `json:"id"`

	// A string value that represents the user’s email address.
	// The email address is either the user’s real email address or the proxy address,
	// depending on their private email relay service.
	Email string `json:"email"`

	// A string or Boolean value that indicates whether the service verifies the email.
	EmailVerified bool `json:"email_verified"`

	// A string or Boolean value that indicates whether the email
	// that the user shares is the proxy address.
	// The value can either be a string ("true" or "false") or a Boolean (true or false).
	IsPrivateEmail bool `json:"is_private_email"`

	// An Integer value that indicates whether the user appears to be a real person.
	// Use the value of this claim to mitigate fraud.
	// The possible values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal).
	RealUserStatus int `json:"real_user_status"`
}

User will have the information of authenticated user of Apple.

type Validation

type Validation interface {

	// Validates request using the authorization code received in an authorization
	// response sent to your app.
	// Returns accessToken, refreshToken, idToken
	ValidateCode(ctx context.Context, code string) (*TokenResponse, error)

	// Validate request using destinatio URI provided in authorization request
	// Returns accessToken, refreshToken, idToken
	ValidateCodeWithRedirectURI(ctx context.Context, code string, redirectURI string) (*TokenResponse, error)

	// Validates given refresh token
	// Returns accessToken and idToken
	ValidateRefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL