Convert Figma logo to code with AI

keycloak logokeycloak

Open Source Identity and Access Management For Modern Applications and Services

26,098
7,156
26,098
1,997

Top Related Projects

11,044

Apereo CAS - Identity & Single Sign On for all earthlings and beyond.

Spring Security

16,121

The only web-scale, fully customizable OpenID Certified™ OpenID Connect and OAuth2 Provider in the world. Become an OpenID Connect and OAuth2 Provider over night. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters. Relied upon by OpenAI and others for web-scale security.

Open source alternative to Auth0 / Firebase Auth / AWS Cognito

26,329

Authentication for the Web.

Quick Overview

Keycloak is an open-source Identity and Access Management solution developed by Red Hat. It provides features such as Single Sign-On (SSO), Identity Brokering, and Social Login for modern applications and services. Keycloak is designed to be easily integrated with various platforms and technologies.

Pros

  • Comprehensive security features, including multi-factor authentication and fine-grained authorization
  • Supports multiple protocols like OpenID Connect, OAuth 2.0, and SAML 2.0
  • Highly customizable and extensible through themes and custom providers
  • Active community and regular updates

Cons

  • Can be complex to set up and configure for advanced use cases
  • Performance may degrade with a large number of concurrent users without proper optimization
  • Limited built-in analytics and reporting capabilities
  • Learning curve for developers new to identity management concepts

Code Examples

  1. Securing a Spring Boot application with Keycloak:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
            .antMatchers("/public*").permitAll()
            .anyRequest().authenticated();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }
}
  1. Retrieving user information in a protected endpoint:
@RestController
public class UserController {

    @GetMapping("/user-info")
    public ResponseEntity<Map<String, Object>> getUserInfo(KeycloakAuthenticationToken authentication) {
        KeycloakPrincipal principal = (KeycloakPrincipal) authentication.getPrincipal();
        KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
        IDToken idToken = session.getIdToken();
        
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", idToken.getPreferredUsername());
        userInfo.put("email", idToken.getEmail());
        userInfo.put("name", idToken.getName());
        
        return ResponseEntity.ok(userInfo);
    }
}
  1. Configuring Keycloak for a React application:
import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
    url: 'https://your-keycloak-server/auth',
    realm: 'your-realm',
    clientId: 'your-client-id'
});

keycloak.init({ onLoad: 'login-required' }).then((authenticated) => {
    if (authenticated) {
        console.log('User is authenticated');
    } else {
        console.log('User is not authenticated');
    }
}).catch((error) => {
    console.error('Failed to initialize Keycloak', error);
});

Getting Started

  1. Download and extract Keycloak from the official website.
  2. Start Keycloak server: bin/standalone.sh (Linux/Mac) or bin\standalone.bat (Windows).
  3. Access the admin console at http://localhost:8080/auth.
  4. Create a new realm and client for your application.
  5. Configure your application to use Keycloak (see code examples above).
  6. Implement authentication and authorization in your application using Keycloak's APIs or SDKs.

Competitor Comparisons

11,044

Apereo CAS - Identity & Single Sign On for all earthlings and beyond.

Pros of CAS

  • More flexible and customizable architecture
  • Stronger support for higher education institutions
  • Extensive plugin ecosystem for additional features

Cons of CAS

  • Steeper learning curve and more complex configuration
  • Less out-of-the-box features compared to Keycloak
  • Smaller community and fewer resources available

Code Comparison

CAS (Java):

@Bean
public ServiceRegistryDao serviceRegistryDao() {
    return new InMemoryServiceRegistry();
}

Keycloak (Java):

@Singleton
public class CustomAuthenticator implements Authenticator {
    @Override
    public void authenticate(AuthenticationFlowContext context) {
        // Custom authentication logic
    }
}

Both projects use Java, but CAS tends to rely more on Spring Framework conventions, while Keycloak uses a more custom approach. CAS configuration often involves Spring beans, whereas Keycloak typically uses SPI interfaces for customization.

CAS offers more flexibility in terms of service registry implementation, allowing for easy swapping between different storage options. Keycloak, on the other hand, provides a more standardized approach to extending authentication flows through its SPI system.

Overall, CAS is more adaptable but requires more effort to set up, while Keycloak offers a more streamlined experience with less initial customization options.

Spring Security

Pros of Spring Security

  • Tightly integrated with Spring ecosystem, offering seamless compatibility with Spring Boot and other Spring projects
  • Highly customizable and flexible, allowing developers to implement complex security scenarios
  • Extensive documentation and large community support

Cons of Spring Security

  • Steeper learning curve, especially for developers new to Spring framework
  • Can be complex to configure for advanced use cases
  • Requires more manual setup compared to Keycloak's out-of-the-box features

Code Comparison

Spring Security configuration example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
            .and().formLogin();
    }
}

Keycloak configuration example:

@Configuration
public class KeycloakConfig {
    @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}

The Spring Security example shows a more detailed configuration, while Keycloak's setup is simpler due to its pre-configured nature. Spring Security offers more granular control, but Keycloak provides a more streamlined approach for standard authentication scenarios.

16,121

The only web-scale, fully customizable OpenID Certified™ OpenID Connect and OAuth2 Provider in the world. Become an OpenID Connect and OAuth2 Provider over night. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters. Relied upon by OpenAI and others for web-scale security.

Pros of Hydra

  • Lightweight and highly performant, designed for high-scale environments
  • Flexible and easily integrable into existing systems
  • Strong focus on OAuth 2.0 and OpenID Connect standards compliance

Cons of Hydra

  • Less comprehensive out-of-the-box features compared to Keycloak
  • Steeper learning curve for initial setup and configuration
  • Smaller community and ecosystem compared to Keycloak

Code Comparison

Hydra (Go):

import "github.com/ory/hydra/client"

c := client.NewHTTPClientWithConfig(nil, &client.TransportConfig{
    Schemes:  []string{"http", "https"},
    Host:     "localhost:4444",
    BasePath: "/",
})

Keycloak (Java):

import org.keycloak.admin.client.Keycloak;

Keycloak keycloak = Keycloak.getInstance(
    "http://localhost:8080/auth",
    "master",
    "admin",
    "password",
    "admin-cli");

Both examples show client initialization, but Hydra's approach is more focused on HTTP transport configuration, while Keycloak's includes authentication details for the admin client.

Open source alternative to Auth0 / Firebase Auth / AWS Cognito

Pros of SuperTokens

  • Lightweight and focused on core authentication functionality
  • Easy to integrate with modern web and mobile applications
  • Extensive documentation and developer-friendly API

Cons of SuperTokens

  • Less mature and smaller community compared to Keycloak
  • Fewer built-in features and integrations out of the box
  • Limited enterprise-level support options

Code Comparison

SuperTokens:

import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
    appInfo: { apiDomain: "...", appName: "..." },
    recipeList: [Session.init()]
});

Keycloak:

import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;

@Configuration
public class KeycloakConfig {
    @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}

The code snippets demonstrate the initialization process for both libraries. SuperTokens uses a more straightforward JavaScript-based configuration, while Keycloak requires Java-based setup with Spring Boot integration.

26,329

Authentication for the Web.

Pros of NextAuth.js

  • Lightweight and easy to integrate with Next.js applications
  • Supports a wide range of authentication providers out-of-the-box
  • Simpler setup and configuration for basic authentication needs

Cons of NextAuth.js

  • Limited advanced features compared to Keycloak's enterprise-grade offerings
  • Less suitable for complex, multi-tenant authentication scenarios
  • Fewer built-in security features and compliance certifications

Code Comparison

NextAuth.js:

import NextAuth from "next-auth"
import Providers from "next-auth/providers"

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    }),
  ],
})

Keycloak:

KeycloakBuilder keycloak = KeycloakBuilder.builder()
    .serverUrl("https://keycloak-server/auth")
    .realm("myrealm")
    .clientId("myclient")
    .clientSecret("client-secret")
    .build();

AccessTokenResponse response = keycloak.tokenManager().grantToken();
String token = response.getToken();

NextAuth.js is more focused on simplicity and ease of use, particularly for Next.js applications. It offers a straightforward setup process and supports various authentication providers. However, it may lack some advanced features and enterprise-grade capabilities that Keycloak provides.

Keycloak, on the other hand, offers a more comprehensive authentication and authorization solution, suitable for complex scenarios and enterprise environments. It provides advanced security features, multi-tenancy support, and extensive customization options, but may require more setup and configuration compared to NextAuth.js.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Keycloak

GitHub Release OpenSSF Best Practices CLOMonitor OpenSSF Scorecard Artifact Hub GitHub Repo stars GitHub commit activity Translation status

Open Source Identity and Access Management

Add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users.

Keycloak provides user federation, strong authentication, user management, fine-grained authorization, and more.

Help and Documentation

Reporting Security Vulnerabilities

If you have found a security vulnerability, please look at the instructions on how to properly report it.

Reporting an issue

If you believe you have discovered a defect in Keycloak, please open an issue. Please remember to provide a good summary, description as well as steps to reproduce the issue.

Getting started

To run Keycloak, download the distribution from our website. Unzip and run:

bin/kc.[sh|bat] start-dev

Alternatively, you can use the Docker image by running:

docker run quay.io/keycloak/keycloak start-dev

For more details refer to the Keycloak Documentation.

Building from Source

To build from source, refer to the building and working with the code base guide.

Testing

To run tests, refer to the running tests guide.

Writing Tests

To write tests, refer to the writing tests guide.

Contributing

Before contributing to Keycloak, please read our contributing guidelines. Participation in the Keycloak project is governed by the CNCF Code of Conduct.

Joining a community meeting is a great way to get involved and help shape the future of Keycloak.

Other Keycloak Projects

License