解析字符串和子字符串

huangapple go评论77阅读模式
英文:

parsing strings and substrings

问题

我正在尝试解码(而不是验证)一个JWT令牌并从其主体中读取值。而且我的代码部分还处理非JWT令牌。因此,我需要处理普通令牌(比如某个字符串)和JWT令牌。

为了实现这一目标,我使用“.”来拆分令牌以读取JWT主体的值,但问题是当我获取非JWT令牌(没有“.”)时会出现“索引超出范围”的问题。

以下是代码示例:

package main

import (
	"fmt"
	"strings"
	"encoding/base64"
	"encoding/json"
)

func main() {
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
	//nonJwtToken := "xxxxxxx"
	
	// 如果传递了非JWT令牌,下面的代码应该优雅地抛出错误
	data, err := base64.RawURLEncoding.DecodeString(strings.Trim(strings.Split(token, ".")[1], "."))
	if err !=nil {
		fmt.Printf("error: ", err)
	}

	var result map[string]interface{}
	err = json.Unmarshal(data, &result)
	fmt.Println(result["name"])
	fmt.Println(err)
}

请注意,我不是在尝试验证JWT,我只是解码JWT并从中读取值。

对此有任何建议将不胜感激。

英文:

I am trying to decode(not validate) a JWT token and read values from its body. And this part of my code also deals with non JWT tokens. So I need to handle both normal tokens (lets say some string) and JWT tokens.

To achieve that, I am splitting token with "." to read JWT body values, but the problem is "index out of range" when I get non JWT tokens(no '.'s)

Go Playground code

package main

import (
	"fmt"
	"strings"
	"encoding/base64"
	"encoding/json"
)

func main() {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
//nonJwtToken := "xxxxxxx"
	
	// below line should gracefull throw error if it passed nonJwtToken
	data, err := base64.RawURLEncoding.DecodeString(strings.Trim(strings.Split(token, ".")[1], "."))
	if err !=nil {
		fmt.Printf("error rahu : " , err)

	}

	var result map[string]interface{}
	err = json.Unmarshal(data, &result)
	fmt.Println(result["name"])
	fmt.Println(err)
	
}

Note that I am not trying to validate JWT, all I am doing is just decoding JWT and reading values from it.

Any suggestions on this would be greatly appreciated.

答案1

得分: 0

根据@RayfenWindspear的评论中提到的,你应该检查Split返回的切片的长度,另外,你不需要从一个以“.”分割的字符串中去掉“.”,因为结果中已经省略了点号。

ts := strings.Split(token, ".")
if len(ts) <= 1 {
    return ErrNonJWTToken
}
data, err := base64.RawURLEncoding.DecodeString(ts[1])

https://play.golang.org/p/NPw7dnBTsh

英文:

As mentioned in the comment by @RayfenWindspear you should check the length of the slice returned by Split, also you don't need to Trim "." from a string that's the result of a split on "." as the dots are omitted from the result.

ts := strings.Split(token, &quot;.&quot;)
if len(ts) &lt;= 1 {
	return ErrNonJWTToken
}
data, err := base64.RawURLEncoding.DecodeString(ts[1])

https://play.golang.org/p/NPw7dnBTsh

huangapple
  • 本文由 发表于 2017年4月14日 03:44:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/43400541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定