I am using Unity Free + NodeJS to code a small project with my mates.
NodeJs for the Server, and Unity for the Clients.
If you entered valid login data, the Server will return a jwt using njwt, which can be decoded using various online tools, and with c#.
But, this Line: byte[] _dec = Convert.FromBase64String(part);
returns no error, but also prevents execution of more code. And I don't know why.
Here are more samples to understand what's going on.
LoginMenu.cs
ws.OnMessage += (sender, e) => {
JObject res = JObject.Parse(e.Data);
switch ((string)res["type"])
{
// If we get a token from the server
// login was successful
case "jwt":
Debug.Log("Res was JWT");
UserAccountManager.instance.LogIn((string)res["jwt"]);
Debug.LogWarning("FINISHED");
break;
// Only 1 case for now
}
};
UserAccountManager.cs
public static UserAccountManager instance;
void Awake() {
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(this);
}
void Set_Jwt(string _jwt)
{
Jwt = _jwt;
Jwt_data = decode_jwt(_jwt);
playerUsername = (string)Jwt_data["username"];
Debug.Log("Jwt set");
Debug.LogWarning(playerUsername);
}
private JObject decode_jwt(string _jwt)
{
string[] splitted = _jwt.Split('.');
var part = splitted[1];
// Code only runs until here
byte[] _dec = Convert.FromBase64String(part);
string decodedjwt = Encoding.UTF8.GetString(_dec);
return JObject.Parse(decodedjwt);
}
public void LogIn(string _jwt) {
Debug.LogWarning("LogIn called");
Set_Jwt(_jwt);
isLoggedIn = true;
Debug.Log("Trying to load " + loggedInSceneName);
SceneManager.LoadScene(loggedInSceneName);
}
EDIT:
I have written almost the same code in a new C# ConsoleApplication, and it throws a System.FormatException: "Invalid Length for base64 Char array"
static void Main(string[] args)
{
string jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJncy5hd2Vzb21lc3R1ZmYuYXQiLCJpYXQiOjE1MTA1OTkyNzQsImV4cCI6MTUxMDYwMjg3MywidWlkIjoiMTY1ZWMxZjAtYzhhNC0xMWU3LTk2ZWQtYzNjNGQ4NTRmM2I4IiwiYXV0aCI6dHJ1ZSwidXNlcm5hbWUiOiJnYWJlbml6aGVyZSIsImlwIjoiMTk0LjIwOC4xMzguMTI4IiwianRpIjoiNjg4NWM0N2YtMjk3NS00N2MyLTgzYTktN2RmMjhmODE3NDljIn0.tRhx3mUbGBxoGFFr0t6dnPMrdlUT4UKJKLBY_9IiJdBePWp1S10Z91875z6OFK92ymACRR_wO3_1_h6fKXAPTQ";
string[] splitted = jwt.Split('.');
var part = splitted[1];
byte[] arr = Convert.FromBase64String(part);
string res = Encoding.UTF8.GetString(arr);
Console.WriteLine(res);
Console.Read();
}
What should I do now?
I finally fixed it. It was a very tiny mistake. The whole token was correct b64, but when I split out the middle part it was dividable by 4. I added a =
and then it decoded fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.