通过使用 JWT token ,我在 golang 上有一个 api,用户必须从该 api 登录,然后访问进一步的 routes
。从下面的代码中,当我点击登录页面的路由时,它将为用户访问它,但是当用户登录时,会生成 token ,但是对于中间件,我们必须从它的 header 中获取 token 以进行 session ,然后我将如何编写html header 中的 token 以及我将如何在 token 验证中访问它。下面是代码:-
路线:-
//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函数
//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
}
}
}
在上面的代码中,当用户登录时, token 将生成并保存在数据库中,但问题是我将如何在 html 页面的标题中写入生成的 token 。另一方面,过去我也使用 postman ,然后生成的 token 将在图像中显示的标题区域中给出。
上面的 token 将在下面给出的验证函数中访问:-
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)
}
}
这些是将我从一个页面重定向到其他页面的 ajax:-
$.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);
}
}
});
上面的 ajax 将在下面给出的这个页面上重定向我
$(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"]
对于 postman ,这将从 header 中获取 token 并将其进行比较。
问题 是我将如何在 Login
函数的 header 中提供 token 以及它将如何在 ValidateToken 中访问
功能如上所示。
如果这个问题是 golang 的基础问题,那么抱歉。谢谢。
最佳答案
您必须发出 Ajax 请求才能在典型的基于浏览器的请求中设置自定义 header :
使用 jQuery,您可以通过以下方式实现:
$(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,
headers: { 'Token': 'YOUR_SECRET' }, // Here your token goes!
type: "GET",
dataType: 'json',
async: false,
data:{"UserId":UserId},
success: function(response){
//my code
}
});
});
在纯 JavaScript 中你可以使用:
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
this.setRequestHeader(Token, 'YOUR_SECRET');
this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
关于ajax - html header中的token怎么写,怎么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50266018/