Presently, I’m studying easy methods to implement http authentication utilizing bearer
tokens, however I don’t know the place to begin. I’ve appeared guides on-line, however
I really feel like I’m lacking one thing. The best way I at the moment do authentication is utilizing gin for routing and bcrypt to retailer the hashed password in hex inside postgresql the place I confirm the hash towards the password offered by the consumer. Under is the instance guides on-line current. Am I presupposed to actually write out the consumer’s username and password for gin’s primary authentication. Additionally how is that this presupposed to work for a newly created
consumer that already listed? Its simply not clear to me.
On-line Implmenetation
package deal essential
import (
"crypto/rand"
"encoding/hex"
"github.com/gin-gonic/gin"
"web/http"
"strings"
)
var tokens []string
func essential() {
r := gin.Default()
r.POST("/login", gin.BasicAuth(gin.Accounts{
"admin": "secret",
}), func(c *gin.Context) {
token, _ := randomHex(20)
tokens = append(tokens, token)
c.JSON(http.StatusOK, gin.H{
"token": token,
})
})
r.GET("/useful resource", func(c *gin.Context) {
bearerToken := c.Request.Header.Get("Authorization")
reqToken := strings.Break up(bearerToken, " ")[1]
for _, token := vary tokens {
if token == reqToken {
c.JSON(http.StatusOK, gin.H{
"knowledge": "useful resource knowledge",
})
return
}
}
c.JSON(http.StatusUnauthorized, gin.H{
"message": "unauthorized",
})
})
r.Run() // Pay attention and serve on 0.0.0.0:8080 (for Home windows "localhost:8080")
}
func randomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Learn(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
refs: