国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java javaTutorial Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Nov 03, 2024 pm 11:10 PM

Introduction:

Single Sign-On (SSO) has become an essential feature in modern web applications, enhancing both user experience and security. This comprehensive guide will walk you through implementing SSO using Keycloak and Spring Boot, providing a robust authentication and authorization solution for your applications.

Importance of SSO with Keycloak

Single Sign-On (SSO) is essential for streamlining authentication processes, enhancing security, and improving user experience. Here are some of the key benefits:

  1. Centralized Authentication: SSO allows users to authenticate once and gain access to multiple applications. Keycloak provides centralized management for user identities, which is useful in environments with numerous applications.

  2. Improved Security: With centralized identity management, security policies (like password strength, two-factor authentication, and account lockout policies) can be uniformly enforced. Keycloak’s support for protocols like OpenID Connect and OAuth 2.0 ensures robust, modern security standards.

  3. Reduced Password Fatigue and Enhanced User Experience: By logging in only once, users avoid password fatigue and multiple credentials, leading to smoother and faster interactions across applications.

  4. Scalability and Flexibility: Keycloak’s configuration can support large numbers of users and multiple identity providers, including social logins (Google, Facebook, etc.) and enterprise directories (LDAP, Active Directory).

  5. Customization and Extensibility: Keycloak allows custom themes, login flows, and extensions, making it adaptable to various needs. It’s also open-source, providing flexibility for organizations to modify or extend the platform as required.
    Alternatives to Single Sign-On (SSO):

  6. Multiple Sign-On / Traditional Authentication:

    • Users have separate credentials for each application or service
    • Requires logging in individually to each system
    • Each application manages its own authentication
  7. Federated Identity:

    • Similar to SSO, but allows authentication across different organizations
    • Uses standards like SAML or OpenID Connect
    • User's identity is verified by their home organization
  8. Multi-Factor Authentication (MFA):

    • Adds additional layers of security beyond just username and password
    • Can be used alongside SSO or traditional authentication
    • Typically involves something you know, have, and are

SSO Flow Explanation:

Before diving into the implementation, let's understand the SSO flow:

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Prerequisites:

  • Java 17 or later
  • Maven
  • Docker (for running Keycloak)

Step 1: Project Setup

Create a new Spring Boot project with the following structure:

keycloak-demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── bansikah/
│   │   │           └── keycloakdemo/
│   │   │               ├── config/
│   │   │               │   └── SecurityConfig.java
│   │   │               ├── controller/
│   │   │               │   └── FoodOrderingController.java
│   │   │               └── KeycloakDemoApplication.java
│   │   └── resources/
│   │       ├── templates/
│   │       │   ├── home.html
│   │       │   └── menu.html
│   │       └── application.yml
├── docker-compose.yml
└── pom.xml

Note:

bansikah is my name ? so you can put yours or example anything you want...

Step 2: Configure pom.xml

Add the following dependencies to your pom.xml or you can just replace the dependency section to avoid conflicts:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity3 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity3</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
    </dependencies>

Step 3: Set up Keycloak with Docker

Create a docker-compose.yml file in the root directory:

version: '3'

services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    environment:
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: admin
    ports:
      - "8088:8080"
    command:
      - start-dev

  app:
    build: .
    ports:
      - "8082:8082"
    depends_on:
      - keycloak

Run the Keycloak server with:

docker-compose up -d

Step 4: Configure Keycloak

  1. Access the Keycloak Admin Console:

    • Go to http://localhost:8088
    • Log in with admin/admin as username and password
  2. Create a New Realm:

    • Go to "Master" at the top left corner
    • Select "Add realm"
    • Name it food-ordering-realm
    • Click "Create"
  3. Create a New Client:
    On the first screen:

    • Set the "Client ID" to "food-ordering-client"
    • Client type: Select "OpenID Connect"
    • Click "Next"

On the next screen (Capability config):

  • Client authentication: Turn this ON (this replaces the old "confidential" setting)
  • Authorization: You can leave this OFF unless you need fine-grained authorization
  • Click "Next"
  1. Client Configuration:
    • Set the root url to http://localhost:8082/
    • Set Access Type to confidential
    • Add Valid Redirect URIs (each URI on a new line):
 http://localhost:8082/
 http://localhost:8082/menu
 http://localhost:8082/login/oauth2/code/keycloak
  • Set Web Origins: http://localhost:8082
  • Click "Save"

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

  1. Retrieve the Client Secret:
    • Go to the Credentials tab
    • Copy the Secret field's value for use in the application configuration

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

  1. Create a User:
    • Go to Users and click "Add user"
    • Set a username (e.g., testuser)
    • In Credentials tab:
      • Set a password
      • Disable "Temporary"

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On
and set the password:

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Step 5: Configure Spring Boot Application

Create application.yml in src/main/resources:

keycloak-demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── bansikah/
│   │   │           └── keycloakdemo/
│   │   │               ├── config/
│   │   │               │   └── SecurityConfig.java
│   │   │               ├── controller/
│   │   │               │   └── FoodOrderingController.java
│   │   │               └── KeycloakDemoApplication.java
│   │   └── resources/
│   │       ├── templates/
│   │       │   ├── home.html
│   │       │   └── menu.html
│   │       └── application.yml
├── docker-compose.yml
└── pom.xml

Replace with the copied secret from Keycloak, usually some random text.
Note:

In production or as a good practice it will be good to keep delicate information as such in a .env file at the root of your project and use it as a variable in your configuration it will be something like ${CLIENT_SECRET} which picks it from the .env file when you start your application, this is also applicable to even the redirect, issuer-uri and the rest..

Step 6: Create Security Configuration

Create SecurityConfig.java in src/main/java/com/bansikah/keycloakdemo/config:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity3 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity3</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
    </dependencies>

Step 7: Create Controller

Create FoodOrderingController.java in src/main/java/com/bansikah/keycloakdemo/controller:

version: '3'

services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    environment:
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: admin
    ports:
      - "8088:8080"
    command:
      - start-dev

  app:
    build: .
    ports:
      - "8082:8082"
    depends_on:
      - keycloak

Step 8: Create HTML Templates

Create home.html in src/main/resources/templates:

docker-compose up -d

Create menu.html in src/main/resources/templates:

 http://localhost:8082/
 http://localhost:8082/menu
 http://localhost:8082/login/oauth2/code/keycloak

Step 9: Run the Application

You should be able to access the application on this url http://localhost:8082 and you should see this

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On
and when you click the here link it takes you to the keycloak form where the user has to authenticate with username and password under the foodorder realm

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

and after authenticated you will see the menu page

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Now with the importance of SSO, even if i logout, i won't have to login again as below

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On
then i can click the link again and i won't be propted to enter my password and username again as below

Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On

Conclusion

Congratulations ?, and Thank you for following up till this time
This implementation demonstrates a robust SSO solution using Keycloak and Spring Boot. It provides a seamless authentication experience while maintaining security. The configuration allows for easy customization and extension to meet specific application needs.
If you encounter any issues or have questions about this implementation, please feel free to leave a comment below. Remember to check the Spring Security and Keycloak documentation for more advanced configurations and features.
Link to code on github

Ref:

  • Spring boot
  • KeyCloak
  • Java 17
  • Maven
  • Docker

The above is the detailed content of Keycloak and Spring Boot: The Ultimate Guide to Implementing Single Sign-On. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Difference between HashMap and Hashtable? Difference between HashMap and Hashtable? Jun 24, 2025 pm 09:41 PM

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

Why do we need wrapper classes? Why do we need wrapper classes? Jun 28, 2025 am 01:01 AM

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

What are static methods in interfaces? What are static methods in interfaces? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

How does JIT compiler optimize code? How does JIT compiler optimize code? Jun 24, 2025 pm 10:45 PM

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

What is an instance initializer block? What is an instance initializer block? Jun 25, 2025 pm 12:21 PM

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

What is the `final` keyword for variables? What is the `final` keyword for variables? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

What is the Factory pattern? What is the Factory pattern? Jun 24, 2025 pm 11:29 PM

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

What is type casting? What is type casting? Jun 24, 2025 pm 11:09 PM

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.

See all articles