Table of Contents
Question content
Solution
Home Backend Development Golang GO authenticate access token (keycloak)

GO authenticate access token (keycloak)

Feb 09, 2024 am 09:30 AM
spring security

GO 验证访问令牌(keycloak)

In modern network applications, security is crucial. In order to protect user data and system resources, verification of access tokens is an essential step. As a powerful identity authentication and access management solution, Keycloak provides developers with a simple and secure verification method. In this article, PHP editor Xigua will introduce how to use Keycloak to verify access tokens to ensure application security. With the guidance of this article, you will be able to easily implement access token verification and ensure that only authorized users can access your application.

Question content

I am trying to implement access token verification using GO. But the examples I've seen online seem to just use TOKEN_SECRET to validate it. But I'm used to programming in Java spring and don't need to use TOKEN_SECRET. I just provide the jwk-set-uri and it checks for validity (auto - security filters etc) and I know it talks to the oauth server and does this validation.

Is there no library in Go that can check if the token is valid by making a request to the oauth server?

I know I know I can do this manually by making a request to the oauth server's userinfo endpoint:

http://localhost:8080/auth/realms/<your_realm>/protocol/openid-connect/userinfo
Copy after login

(Include token in header with key authorization)

But I don't know if this fully meets the criteria.

What is the correct approach?

Solution

Short answer: Use go-oidc

Long answer: First, let’s understand how Spring Security automatically validates JWT access tokens. By convention, if you define OAuth 2.0 or OIDC client properties in the application.yaml configuration file, Spring will automatically wire up a filter in the security filter chain, getting jwk- set, Keycloak is a set of public keys corresponding to the keys Keycloak uses to sign tokens. The filter will be applied to all protected routes and spring will use the public key to check that the token's signature is valid and make other checks if applicable (audience, timeout, etc...)

So how do we do this in Go? We can write a simple middleware that accepts jwk-set and uses it to validate the token. You need to check the alg declaration to see which signature algorithm was used, select the corresponding public key from jwk-set and check that the signature is valid. Then, decode the token, confirm the iss and sub claims to ensure it comes from a trusted issuer and is intended for the intended audience, and check that it has not expired. Check that the times declared by nbf (not before) and iat (issued after) are correct. Finally, relevant information from the token is injected into the request context if needed downstream.

func JWTMiddleware(jwkSet map[string]*rsa.PublicKey) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            authHeader := r.Header.Get("Authorization")
            if authHeader == "" {
                http.Error(w, "Authorization header is required", http.StatusUnauthorized)
                return
            }

            tokenString := strings.TrimPrefix(authHeader, "Bearer ")
            token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
                if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
                    return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
                }

                alg := token.Method.Alg()
                publicKey, ok := jwkSet[alg]
                if !ok {
                    return nil, fmt.Errorf("no key found for signing method: %v", alg)
                }
                return publicKey, nil
            })
            
            if err != nil || !token.Valid {
                http.Error(w, "Invalid token", http.StatusUnauthorized)
                return
            }
            // Other checks, ISS, Aud, Expirey, etc ...
            // If needed, store the user principal 
            // and other relevant info the request context  
            next.ServeHTTP(w, r)
        })
    }
}
Copy after login

The above is the detailed content of GO authenticate access token (keycloak). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Security 6: cors() is deprecated and marked for removal Spring Security 6: cors() is deprecated and marked for removal Feb 10, 2024 pm 11:45 PM

I have the following code: publicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{returnhttp.httpBasic().disable().cors().and().csrf().disable().authorizeHttpRequests().requestMatchers("

How to develop a Spring Security SAML-based single sign-on system using Java How to develop a Spring Security SAML-based single sign-on system using Java Sep 22, 2023 am 08:49 AM

How to use Java to develop a single sign-on system based on SpringSecuritySAML Introduction: With the rapid development of the Internet, more and more applications are developed. In these applications, user login is one of the most common features. However, for enterprise-level applications, users need to log in in multiple systems, which will lead to a very poor user login experience. In order to solve this problem, the single sign-on system (SingleSign-On, referred to as SSO) came into being. simple

GO authenticate access token (keycloak) GO authenticate access token (keycloak) Feb 09, 2024 am 09:30 AM

I'm trying to implement access token validation using GO. But the examples I've seen online seem to just use TOKEN_SECRET to verify it. But I'm used to programming in Javaspring and don't need to use TOKEN_SECRET. I just provide the jwk-set-uri and it checks for validity (auto-security filters etc.) and I know it talks to the oauth server and does this validation. Is there no library in Go to check if the token is valid by making a request to the oauth server? I know I know I can do this manually by making a request to the oauth server's userinfo endpoint: http://localh

Spring Security permission control framework usage guide Spring Security permission control framework usage guide Feb 18, 2024 pm 05:00 PM

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.

How to use Java to develop a single sign-on system based on Spring Security OAuth2 How to use Java to develop a single sign-on system based on Spring Security OAuth2 Sep 20, 2023 pm 01:06 PM

How to use Java to develop a single sign-on system based on SpringSecurityOAuth2 Introduction: With the rapid development of the Internet, more and more websites and applications require users to log in, but users do not want to remember for each website or application. An account number and password. The single sign-on system (SingleSign-On, referred to as SSO) can solve this problem, allowing users to access multiple websites and applications without repeated authentication after logging in once. This article will introduce

Spring Security gets user information for authenticated and unauthenticated users in remaining services Spring Security gets user information for authenticated and unauthenticated users in remaining services Feb 08, 2024 pm 11:00 PM

I have a springrest service and I want to use it for both authenticated and unauthenticated users. If the user is authenticated, I want to get the user information from securitycontextholder.getcontext().getauthentication(). If I use .antmatchers("/app/rest/question/useroperation/list/**").permitall() in the ouath2 configuration as shown below, then I can get the user information of the authenticated user, but not Authenticated users will appear 40

The Java RESTful API cookbook: Building the perfect service for every application The Java RESTful API cookbook: Building the perfect service for every application Mar 27, 2024 pm 12:11 PM

Introduction In today's interconnected world, RESTful APIs have become a key mechanism for communication between applications. With Java, a powerful programming language, you can build efficient, scalable, and well-maintained RESTful APIs. Chapter 1: RESTfulAPI Basics Principles and Best Practices of RESTful Architecture Http methods, status codes and response headers Data formats such as JSON and XML Chapter 2: Design and Modeling RESTfulAPI RESTfulAPI Design Principles Resource Modeling and URI Design Version Control and HATEOAS Chapter 3: Using SpringBoot to build RESTful API SpringBoot introduction and getting started building and

How do the vue framework and the springboot framework interact with the front and back ends? How do the vue framework and the springboot framework interact with the front and back ends? Apr 06, 2024 am 01:51 AM

Vue.js and Spring Boot interact through: RESTful API: Vue.js uses Axios to send asynchronous HTTP requests, and Spring Boot provides a RESTful API implementation. Data passing: Data is passed through requests and responses, such as the request body or query parameters. Request method: HTTP request methods such as GET, POST, PUT, and DELETE are used to specify the operation. Routing: Spring Boot @RequestMapping annotation defines controller routing, and Vue.js uses Vue Router to define interface routing. State management: Vu

See all articles