Convert Figma logo to code with AI

spring-projects logospring-authorization-server

Spring Authorization Server

4,844
1,280
4,844
48

Top Related Projects

Spring Security

22,126

Open Source Identity and Access Management For Modern Applications and Services

10,852

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

10,174

Java JWT: JSON Web Token for Java and Android

Java implementation of JSON Web Token (JWT)

Quick Overview

Spring Authorization Server is an OAuth 2.1 and OpenID Connect 1.0 compliant authorization server built on top of the Spring Framework and Spring Security. It provides a robust and customizable solution for implementing authentication and authorization in Spring-based applications.

Pros

  • Fully compliant with OAuth 2.1 and OpenID Connect 1.0 standards
  • Seamless integration with Spring ecosystem and Spring Security
  • Highly customizable and extensible architecture
  • Active development and community support

Cons

  • Steep learning curve for developers new to OAuth and OpenID Connect
  • Limited documentation compared to more established alternatives
  • Still in active development, which may lead to breaking changes in future releases
  • Requires significant configuration for advanced use cases

Code Examples

  1. Configuring the Authorization Server:
@Configuration
public class AuthorizationServerConfig {

    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("client")
                .clientSecret("{noop}secret")
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                .redirectUri("http://127.0.0.1:8080/login/oauth2/code/client")
                .scope(OidcScopes.OPENID)
                .scope("read")
                .build();

        return new InMemoryRegisteredClientRepository(registeredClient);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        RSAKey rsaKey = generateRsa();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://auth-server:9000").build();
    }
}
  1. Configuring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            )
            .formLogin(withDefaults());
        return http.build();
    }

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}
  1. Configuring a Resource Server:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

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

Getting Started

  1. Add the Spring Authorization Server dependency to your pom.xml:
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>0.3.1</version>
</dependency>
  1. Configure the Authorization Server as shown in the code examples above.

  2. Run your Spring Boot application and access the authorization server endpoints:

    • Authorization endpoint: http://localhost:9000/oauth2/authorize
    • Token endpoint: http://localhost:9000/oauth2/token
    • JWK Set endpoint: http://localhost:9000/oauth2/jwks

Competitor Comparisons

Spring Security

Pros of Spring Security

  • Broader scope, covering various security aspects beyond authorization
  • More mature and established project with extensive documentation
  • Wider community support and ecosystem integration

Cons of Spring Security

  • Can be complex to configure for specific use cases
  • Heavier footprint due to its comprehensive feature set
  • May require more setup for OAuth 2.0 and OpenID Connect scenarios

Code Comparison

Spring Security (basic configuration):

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

Spring Authorization Server (basic configuration):

@Configuration
@Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {
    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        // Configure registered clients
    }
}

Spring Security provides a more general security configuration, while Spring Authorization Server focuses specifically on OAuth 2.0 and OpenID Connect implementation. Spring Security requires more explicit configuration for various security aspects, whereas Spring Authorization Server offers a more streamlined setup for authorization server functionality.

22,126

Open Source Identity and Access Management For Modern Applications and Services

Pros of Keycloak

  • More comprehensive out-of-the-box features, including user management and identity brokering
  • Supports multiple protocols (OpenID Connect, SAML, OAuth 2.0) natively
  • Offers a user-friendly admin console for easier configuration and management

Cons of Keycloak

  • Heavier resource footprint, potentially less suitable for lightweight applications
  • Steeper learning curve due to its extensive feature set
  • Less seamless integration with Spring ecosystem compared to Spring Authorization Server

Code Comparison

Spring Authorization Server:

@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
    return http.formLogin(Customizer.withDefaults()).build();
}

Keycloak:

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.authorizeRequests()
        .antMatchers("/customers*").hasRole("USER")
        .antMatchers("/admin*").hasRole("ADMIN")
        .anyRequest().permitAll();
}

Both repositories provide robust authorization server implementations, but they cater to different use cases. Spring Authorization Server is more lightweight and integrates seamlessly with the Spring ecosystem, while Keycloak offers a more comprehensive identity and access management solution with additional features and protocols support.

10,852

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

Pros of CAS

  • More comprehensive feature set, including multi-factor authentication and advanced ticketing mechanisms
  • Longer history and wider adoption in enterprise environments
  • Extensive documentation and community support

Cons of CAS

  • Steeper learning curve due to its complexity and extensive features
  • Potentially heavier resource consumption compared to Spring Authorization Server

Code Comparison

CAS (Groovy configuration):

cas.authn.accept.users=casuser::Mellon
cas.service-registry.json.location=file:/etc/cas/services
cas.authn.mfa.global-provider-id=mfa-duo

Spring Authorization Server (Java configuration):

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("client")
            .clientSecret("{noop}secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUri("http://127.0.0.1:8080/login/oauth2/code/client")
            .scope("openid")
            .build();
    return new InMemoryRegisteredClientRepository(registeredClient);
}
10,174

Java JWT: JSON Web Token for Java and Android

Pros of JJWT

  • Lightweight and focused solely on JWT operations
  • Easy to integrate into existing projects without additional dependencies
  • Supports a wide range of cryptographic algorithms

Cons of JJWT

  • Lacks built-in OAuth 2.0 and OpenID Connect support
  • Requires manual implementation of security features and token management
  • Limited to JWT-specific functionality

Code Comparison

JJWT:

String jws = Jwts.builder()
    .setSubject("user123")
    .signWith(SignatureAlgorithm.HS256, key)
    .compact();

Spring Authorization Server:

OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient =
    new DefaultAuthorizationCodeTokenResponseClient();
OAuth2AccessTokenResponse tokenResponse = accessTokenResponseClient.getTokenResponse(authorizationCodeGrantRequest);

Summary

JJWT is a lightweight library focused on JWT operations, making it easy to integrate into existing projects. It supports various cryptographic algorithms but lacks built-in OAuth 2.0 and OpenID Connect support.

Spring Authorization Server provides a comprehensive OAuth 2.0 and OpenID Connect solution, offering more robust security features and token management. However, it may be overkill for projects that only require simple JWT functionality.

Choose JJWT for straightforward JWT operations in existing projects, and Spring Authorization Server for full-fledged OAuth 2.0 and OpenID Connect implementations.

Java implementation of JSON Web Token (JWT)

Pros of java-jwt

  • Lightweight and focused solely on JWT handling
  • Easy to integrate into existing projects without additional dependencies
  • Supports various algorithms for JWT signing and verification

Cons of java-jwt

  • Limited to JWT operations, lacking comprehensive authorization server features
  • Requires manual implementation of token issuance, validation, and management
  • No built-in support for OAuth 2.0 flows or OpenID Connect

Code Comparison

spring-authorization-server:

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("client")
            .clientSecret("{noop}secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUri("http://127.0.0.1:8080/login/oauth2/code/client")
            .scope(OidcScopes.OPENID)
            .build();
    return new InMemoryRegisteredClientRepository(registeredClient);
}

java-jwt:

Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
        .withIssuer("auth0")
        .withClaim("username", "john.doe")
        .withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000))
        .sign(algorithm);

The spring-authorization-server example showcases client registration for OAuth 2.0, while java-jwt demonstrates simple JWT creation and signing.

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

= Spring Authorization Server image:https://badges.gitter.im/Join%20Chat.svg[Gitter,link=https://gitter.im/spring-projects/spring-security?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge] image:https://github.com/spring-projects/spring-authorization-server/actions/workflows/continuous-integration-workflow.yml/badge.svg["Build Status", link="https://github.com/spring-projects/spring-authorization-server/actions/workflows/continuous-integration-workflow.yml"] image:https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A["Revved up by Develocity", link="https://ge.spring.io/scans?&search.rootProjectNames=spring-authorization-server"]

The Spring Authorization Server project, led by the https://spring.io/projects/spring-security/[Spring Security] team, is focused on delivering https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-07#section-1.1[OAuth 2.1 Authorization Server] support to the Spring community.

This project replaces the Authorization Server support provided by https://spring.io/projects/spring-security-oauth/[Spring Security OAuth].

== Feature Planning This project uses https://docs.github.com/en/issues/planning-and-tracking-with-projects/learning-about-projects/about-projects[GitHub Projects] to prioritize the feature roadmap and help organize the project plan. The project board can be accessed https://github.com/orgs/spring-projects/projects/8[here].

The feature list can be viewed in the https://docs.spring.io/spring-authorization-server/reference/overview.html#feature-list[reference documentation].

== Support Policy The Spring Authorization Server project provides software support through the https://tanzu.vmware.com/support/oss[VMware Tanzu OSS support policy]. https://tanzu.vmware.com/spring-runtime[Commercial support], which offers an extended support period, is also available from VMware.

== Getting Started The first place to start is to read the https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11[OAuth 2.1 Authorization Framework] to gain an in-depth understanding on how to build an Authorization Server. It is a critically important first step as the implementation must conform to the specification defined in the OAuth 2.1 Authorization Framework and the https://github.com/spring-projects/spring-authorization-server/wiki/OAuth-2.0-Specifications[related specifications].

The second place to start is to become very familiar with the codebase in the following Spring Security modules:

A significant amount of effort was put into developing the https://spring.io/blog/2018/01/30/next-generation-oauth-2-0-support-with-spring-security[Next Generation OAuth 2.0 Support in Spring Security]. The goal is to leverage all the knowledge learned thus far and apply the same to the development of Spring Authorization Server.

Submitted work via pull requests should follow the same coding style/conventions and adopt the same or similar design patterns that have been established in Spring Security's OAuth 2.0 support.

== Documentation Be sure to read the https://docs.spring.io/spring-authorization-server/reference/[Spring Authorization Server Reference] and https://docs.spring.io/spring-security/reference[Spring Security Reference], as well as the https://docs.spring.io/spring-security/reference/servlet/oauth2/index.html[OAuth 2.0 Reference], which describes the Client and Resource Server features available.

JavaDoc is also available for the https://docs.spring.io/spring-authorization-server/docs/current/api/[Spring Authorization Server API] and https://docs.spring.io/spring-security/site/docs/current/api/[Spring Security API].

== Code of Conduct Please see our https://github.com/spring-projects/.github/blob/main/CODE_OF_CONDUCT.md[code of conduct].

== Downloading Artifacts See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Artifacts[downloading Spring artifacts] for Maven repository information.

== Building from Source Spring Authorization Server uses a https://gradle.org[Gradle]-based build system. In the instructions below, https://vimeo.com/34436402[`./gradlew`] is invoked from the root of the source tree and serves as a cross-platform, self-contained bootstrap mechanism for the build.

=== Prerequisites https://help.github.com/set-up-git-redirect[Git] and the https://www.oracle.com/technetwork/java/javase/downloads[JDK17 build].

Be sure that your JAVA_HOME environment variable points to the jdk17 folder extracted from the JDK download.

=== Check out sources [indent=0]

git clone git@github.com:spring-projects/spring-authorization-server.git


=== Install all spring-* jars into your local Maven cache [indent=0]

./gradlew publishToMavenLocal

=== Compile and test; build all jars, distribution zips, and docs [indent=0]

./gradlew build

Discover more commands with ./gradlew tasks.

== Getting Support Check out the https://stackoverflow.com/questions/tagged/spring-authorization-server[Spring Authorization Server tags on Stack Overflow]. https://spring.io/support[Commercial support] is available too.

== Contributing https://help.github.com/articles/creating-a-pull-request[Pull requests] are welcome; see the link:CONTRIBUTING.adoc[contributor guidelines] for details.

== License Spring Authorization Server is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].