github.com/greenpau/go-authcrunch@v1.1.4/pkg/kms/parsers.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package kms
    16  
    17  import (
    18  	"encoding/base64"
    19  	"encoding/json"
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  // ParsePayloadFromToken extracts payload from a token.
    25  func ParsePayloadFromToken(s string) (map[string]interface{}, error) {
    26  	m := make(map[string]interface{})
    27  	arr := strings.SplitN(s, ".", 3)
    28  	if len(arr) != 3 {
    29  		return nil, fmt.Errorf("malformed token")
    30  	}
    31  	payload := arr[1]
    32  	if i := len(payload) % 4; i != 0 {
    33  		payload += strings.Repeat("=", 4-i)
    34  	}
    35  	var decodedStr []byte
    36  	var err error
    37  	if strings.ContainsAny(payload, "/+") {
    38  		// This decoding works with + and / signs. (legacy)
    39  		decodedStr, err = base64.StdEncoding.DecodeString(payload)
    40  	} else {
    41  		// This decoding works with - and _ signs.
    42  		decodedStr, err = base64.URLEncoding.DecodeString(payload)
    43  	}
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	if err := json.Unmarshal(decodedStr, &m); err != nil {
    48  		return nil, err
    49  	}
    50  	return m, nil
    51  }