I am making an authentication form on my web app.
First, I send the form data to server, it produces the token and I store it in the localStorage
Then, I want to redirect from form page to the home page. Here is the JavaScript that sends the token to server so that I would be seen as an authorized user on the home page:
const xhr = new XMLHttpRequest()
xhr.open('GET', '/')
xhr.setRequestHeader('Authorization', localStorage.token)
xhr.send()
xhr.onload = () => {
if(xhr.status >= 400) {
console.log("error")
}
}
xhr.onerror = () => {
console.log("error")
}
Then I want to check the token and show the home page. Here is the Golang func for it:
func (h *Handler) Home_page(c *gin.Context) {
header := c.GetHeader("Authorization")
if header != "" {
_, err := h.services.Authorization.ParseToken(header)
if err != nil {
newErrorResponse(c, http.StatusUnauthorized, err.Error())
return
}
c.HTML(
http.StatusOK,
"home_page.gohtml",
gin.H{
"IsAuth": true,
},
)
return
}
}
ParseToken func:
func (s *AuthService) ParseToken(accessToken string) (int, error) {
token, err := jwt.ParseWithClaims(accessToken, &tokenClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("invalid signing method")
}
return []byte(signingKey), nil //signingKey is a string with random elements
})
if err != nil {
return 0, err
}
claims, ok := token.Claims.(*tokenClaims)
if !ok {
return 0, errors.New("token claims are not of type *tokenClaims")
}
return claims.UserId, nil
}
The problem is that I get this error:
ERRO[0001] illegal base64 data at input byte 0
I already checked the token on the jwt.io, it shows that the token is verified, maybe the problem is in the type of string that I am passing as a token.
Another problem is that if I don't check the error returning from token validation, the home page doesn't show with this error:
http: panic serving [::1]:50490: write tcp [::1]:8083->[::1]:50490: write: broken pipe
I am new to Golang, was struggling with this problem, though it seems typical.
I would be very thankful for any help on how to process the token or to redirect from the authentication form!
Edit: I am using the https://github.com/golang-jwt/jwt/v4
CodePudding user response:
Somehow, this issue: illegal base64 data at input byte 0
Was solved by changing the way I stored the token. I was storing in the local storage like this:
localStorage.setItem('token', data.token)
I changed it to the next line and the error disappeared:
localStorage.token = data.token
(data is the JSON with token that my server returns)
Now if I log the value of token it appears without commas. @Crowman, thank you for answer!
Edit: The second issue with broken pipe occurred, because I was not waiting for the answer on the client side. So now I changed the JS code to wait for the response but still I am struggling with how to show the html page that I receive from server using JavaScript.
