By using JWT tokens I have an api on golang from which user will have to login and then access the further routes
. From below code when I will hit the route of login page then it will access it for user but when user login then token is generated and but for middleware we have to take the token from it header for making a session then how I will write the token in the html header and how i will access it in validation of the token. Below is the code:-
Routes:-
//routes which are available for any user
router := gin.New()
main := router.Group("/api/v2")
{
main.GET("/signup",controller.Signup)
main.POST("/customer/new",controller.SaveCustomer)
main.GET("/login",controller.Users)
main.POST("/login",controller.Login)
}
router.Use(JWTAuthMiddleware())
//routes for authorized user
v1 := router.Group("/api/v1")
//routes for v1 group for onlu authorized user
Controller.Login function
//struct
type User struct {
Email string `json:"email"`
Password string `json:"password"`
jwt.StandardClaims
}
func Login(c *gin.Context) {
c.Request.ParseForm()
email := c.PostForm("email")
password := c.PostForm("password")
response := ResponseControllerList{}
conditions := bson.M{"email":email,"password":password}
data, err := models.MatchUser(conditions)
if err!=nil {
fmt.Println(err)
}
fmt.Println(data)
dataCount, err := models.GetRecordsCount(config.CustomerCollection, conditions)
counter:= 0
for _, signup := range data {
if email == signup.Email && password == signup.Password {
//fmt.Println("heloo")
counter = 1
}
}
if data == nil {
response = ResponseControllerList{
config.FailureCode,
config.FailureFlag,
config.FailureMsg,
config.UsernamePassword,
nil,
}
} else {
response = ResponseControllerList{
config.SuccessFlag,
config.SuccessFlag,
config.SuccessMsg,
data,
dataCount,
}
}
GetResponseList(c, response)
if counter == 1 {
fmt.Println("Match!")
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), &User{
Email: email,
Password: password,
})
fmt.Println(token)
tokenstring, err := token.SignedString([]byte(""))
if err != nil {
fmt.Println(err)
}
fmt.Println(tokenstring)
var tok models.Token
tokenErr := json.NewDecoder(c.Request.Body).Decode(&tok)
tok.Tok = tokenstring
if tokenErr = nil {
fmt.Println("error")
}
err = models.SaveToken(&tok)
if err != nil {
fmt.Println("error while saving the token")
}else{
fmt.Println("successfully saved")//here the token will saved
}
}
}
On the above code there when the user will login then the token will generate and will save in the database but issue is how I will write the generated token in the header of the html page. On the other hand in past I also used postman for it then the generated token will given in the header area show in the image.
This above token will access in the validating function given below:-
func ValidateToken(c *gin.Context) {
headerToken := c.Request.Header["Token"]
response := ResponseUser{}
headerTok := strings.Join(headerToken," ")
condition := bson.M{"token":headerTok}
data, err := models.MatchToken(condition)// matches the token.
if err != nil {
fmt.Println("Errorrr")
}
counter:= 0
for _, stringData := range data {
if stringData.Tok == headerTok {
counter = 1
}
}
if counter == 1 {
fmt.Println("Authorized user")
c.Next()
}else{
fmt.Println("Unauthorized User")
response = ResponseUser{
"Unauthorized User",
}
c.AbortWithStatus(401)
Response(c, response)
}
}
These are the ajax which are redirecting me from one page to other:-
$.ajax({
url:"/api/v2/login",
type:"POST",
data: {'email':email, "password":password},
success: function(results) {
console.log(results)
if(results.response.message === "Success"){
console.log("hello")
alert(results.response.message);
document.location.href = "/api/v1/customer?Number="+results.response.data[0]._id;
}
if(results.response.message === "Failure"){
console.log("hello")
alert(results.response.data);
}
}
});
The above ajax will redirect me on this page ajax given below
$(document).ready(function(){
$('#activate').hide();
var full_url = document.URL; // Get current url
var url_array = full_url.split('=') // Split the string into an array with / as separator
var UserId = url_array[url_array.length-1]; // Get the last part of the array (-1)
$.ajax({
url:"/api/v1/customer/get-data?Last="+UserId,
type: "GET",
dataType: 'json',
async: false,
data:{"UserId":UserId},
success: function(response){
//my code
}
});
});
headerToken := c.Request.Header["Token"]
For postman this will take the token from the header and will compare it.
ISSUE is that how I will give the token in the header in Login
function and how It will access in the ValidateToken
function as show above.
If this question is basic for golang then sorry. Thank you.