search
HomeBackend DevelopmentGolangImplement basic API authentication and authorization using Go

Implement basic API authentication and authorization using Go

Jun 17, 2023 pm 07:51 PM
goAuthorizeapi certification

With the continuous development of web applications, as applications gradually become larger and larger, API interfaces need to be protected to prevent random access, so API authentication and authorization mechanisms become more and more important. In this article, we will introduce how to use Go to implement basic API authentication and authorization.

First, let’s understand the basic concepts of authentication and authorization:

Authentication: Authentication is an identity verification mechanism used to verify whether the identity requested by the user is legitimate. In web applications, authentication can be through username and password or using tokens such as JWT.

Authorization: Authorization is a permission verification mechanism used to determine whether the user has the right to access the requested resource. In web applications, authorization can be performed through role-based access control or access tokens.

Implementing basic API authentication and authorization in Go can be divided into the following steps:

Step 1: Install and configure the Gin framework

Before using the Gin framework, you need to first Install it. We can install it using the following command:

go get -u github.com/gin-gonic/gin

After the installation is complete, we can initialize the Gin framework using the following code:

import "github.com/gin-gonic/gin"

router := gin.Default()

Step 2: Add routing

Before we start adding Before routing, you need to define a middleware function to verify whether the user is legitimate. The middleware function checks the incoming request headers and returns a status code and error message to the handler.

func AuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // 验证用户是否合法
        if userValid {
            c.Set("user", "valid")
            c.Next()
        } else {
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
        }
    }
}

We can add middleware functions in the routing function to ensure that only authenticated users can access the required resources.

router.GET("/secured", AuthMiddleware(), func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"message": "You are authorized to access this resource"})
})

In the above code, the GET request will be routed to the /secured endpoint, but only authenticated users will be able to access it successfully.

Step 3: Implement JWT authentication

Now, we have added a route and used middleware to ensure that the user is authenticated to access the route. Next, we'll look at how to authenticate users using JWT.

JWT is a JSON-based web token that provides a secure way to transfer information between clients and servers. JWT usually consists of three parts: header, payload and signature. The header contains the token type and signature algorithm, the payload contains the token data, and the signature is used to verify the integrity of the token.

We can use the following code to implement JWT authentication in Go:

import (
    "time"

    "github.com/dgrijalva/jwt-go"
)

func CreateToken() (string, error) {
    token := jwt.New(jwt.SigningMethodHS256)
    claims := token.Claims.(jwt.MapClaims)
    claims["user"] = "john@example.com"
    claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

    tokenString, err := token.SignedString([]byte("secret"))
    if err != nil {
        return "", err
    }

    return tokenString, nil
}

In the above code, we first create a JWT token and then add a user claim and expiration time. Finally, the token is signed and the result is returned.

Step 4: Implement role-based authorization

In the final step, we will learn how to use role-based authorization to control user access to resources.

In role-based access control, users are assigned to one or more roles, and each role is granted a set of permissions. When accessing resources, the authorization center determines which resources the user has access to based on their role.

We can use the following code to implement a simple role-based authorization:

func AuthzMiddleware(roles ...string) gin.HandlerFunc {
    return func(c *gin.Context) {
        userRole := "admin" // 从数据库或其他地方获取用户角色

        for _, role := range roles {
            if role == userRole {
                c.Next()
                return
            }
        }

        c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
    }
}

In the above code, we define an AuthzMiddleware middleware function, which accepts a role list as a parameter, and check if the user role is included. If the user has the required role, pass the middleware and proceed to the next handler; otherwise, return a Forbidden status code.

Finally, we can add the AuthzMiddleware function to the route to ensure that only users with specific roles can access the required resources.

router.GET("/admin", AuthMiddleware(), AuthzMiddleware("admin"), func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"message": "You are authorized to access this resource"})
})

The above are the basic steps for using Go to implement basic API authentication and authorization. These basic implementations can serve as the basis for an application and can be further customized and extended as needed.

The above is the detailed content of Implement basic API authentication and authorization using Go. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment