spring-security-oauth
Support for adding OAuth1(a) and OAuth2 features (consumer and provider) for Spring web applications.
Top Related Projects
Spring Security
Spring Authorization Server
Open Source Identity and Access Management For Modern Applications and Services
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...
Apereo CAS - Identity & Single Sign On for all earthlings and beyond.
Java JWT: JSON Web Token for Java and Android
Quick Overview
Spring Security OAuth is a deprecated project that provided OAuth 1.0 and OAuth 2.0 support for Spring applications. It was part of the Spring ecosystem and offered integration with Spring Security for authentication and authorization using OAuth protocols.
Pros
- Seamless integration with Spring Security and other Spring projects
- Supported both OAuth 1.0 and OAuth 2.0 protocols
- Provided comprehensive documentation and examples
- Offered flexibility in configuring OAuth providers and clients
Cons
- Deprecated and no longer maintained
- Complex configuration for some use cases
- Limited support for newer OAuth 2.0 features
- Potential security vulnerabilities due to lack of updates
Code Examples
- Configuring an OAuth 2.0 client:
@Configuration
@EnableOAuth2Client
public class OAuth2ClientConfig {
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
return new OAuth2RestTemplate(details, oauth2ClientContext);
}
}
- Protecting a resource with OAuth 2.0:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll();
}
}
- Configuring an OAuth 2.0 authorization server:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client-id")
.secret("client-secret")
.authorizedGrantTypes("authorization_code", "refresh_token")
.scopes("read", "write")
.redirectUris("http://localhost:8080/callback");
}
}
Getting Started
To use Spring Security OAuth in a Spring Boot application:
- Add the dependency to your
pom.xml
:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.5.2.RELEASE</version>
</dependency>
- Enable OAuth 2.0 client support in your main application class:
@SpringBootApplication
@EnableOAuth2Client
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- Configure OAuth 2.0 properties in
application.yml
:
security:
oauth2:
client:
clientId: your-client-id
clientSecret: your-client-secret
accessTokenUri: https://example.com/oauth/token
userAuthorizationUri: https://example.com/oauth/authorize
resource:
userInfoUri: https://example.com/oauth/userinfo
Note: As this project is deprecated, it's recommended to use Spring Security's built-in OAuth 2.0 support or other maintained alternatives for new projects.
Competitor Comparisons
Spring Security
Pros of Spring Security
- More actively maintained and regularly updated
- Broader scope, covering various security aspects beyond OAuth
- Better integration with the Spring ecosystem
Cons of Spring Security
- Steeper learning curve due to its comprehensive nature
- May be overkill for simple OAuth-only implementations
- Requires more configuration for basic OAuth setups
Code Comparison
Spring Security OAuth:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
// OAuth2 server configuration
}
Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login();
}
}
Key Differences
- Spring Security OAuth is focused solely on OAuth and OpenID Connect
- Spring Security provides a more comprehensive security solution
- Spring Security OAuth is now in maintenance mode, while Spring Security is actively developed
- Spring Security requires more setup for OAuth but offers greater flexibility
- Spring Security OAuth has simpler configuration for basic OAuth scenarios
Recommendation
Choose Spring Security for new projects or when requiring a full security solution. Opt for Spring Security OAuth only if maintaining legacy projects or needing a lightweight OAuth-specific implementation.
Spring Authorization Server
Pros of spring-authorization-server
- More modern and actively maintained
- Better alignment with latest OAuth 2.0 and OpenID Connect specifications
- Improved security features and best practices
Cons of spring-authorization-server
- Less mature and potentially fewer community resources
- May require migration efforts for existing spring-security-oauth users
- Steeper learning curve for developers familiar with the older library
Code Comparison
spring-security-oauth:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("client-id").secret("secret").scopes("read", "write");
}
}
spring-authorization-server:
@Configuration
@Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient client = RegisteredClient.withId("client-id")
.clientSecret("secret").scopes("read", "write").build();
return new InMemoryRegisteredClientRepository(client);
}
}
The spring-authorization-server example demonstrates a more modular and flexible approach to client configuration, utilizing the RegisteredClientRepository for managing client details.
Open Source Identity and Access Management For Modern Applications and Services
Pros of Keycloak
- Comprehensive identity and access management solution with a wide range of features
- Active development and regular updates
- Supports multiple protocols and standards out of the box (OAuth 2.0, OpenID Connect, SAML)
Cons of Keycloak
- Steeper learning curve due to its extensive feature set
- Requires more resources to run compared to Spring Security OAuth
- May be overkill for simple authentication scenarios
Code Comparison
Spring Security OAuth:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
// Configuration code here
}
Keycloak:
@Configuration
public class KeycloakConfig {
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}
Additional Notes
- Spring Security OAuth is now in maintenance mode, while Keycloak is actively developed
- Keycloak offers a user-friendly admin console for managing users, roles, and clients
- Spring Security OAuth integrates more seamlessly with Spring Boot applications
- Keycloak provides built-in support for social login and user federation
- Both projects have extensive documentation, but Keycloak's is more comprehensive due to its broader feature set
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...
Pros of pac4j
- Multi-protocol support: Handles various authentication mechanisms (OAuth, SAML, OpenID Connect, etc.)
- Framework-agnostic: Can be integrated with different Java web frameworks
- Active development and community support
Cons of pac4j
- Steeper learning curve due to its flexibility and extensive features
- Less Spring-specific optimizations compared to Spring Security OAuth
Code Comparison
pac4j:
Config config = new Config(new GoogleOidcClient(clientId, clientSecret));
SecurityFilter filter = new SecurityFilter(config, "GoogleOidcClient");
Spring Security OAuth:
@EnableOAuth2Client
public class OAuth2ClientConfig {
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext context) {
return new OAuth2RestTemplate(google(), context);
}
}
Key Differences
- pac4j offers a more generic approach, suitable for various Java frameworks
- Spring Security OAuth is tightly integrated with the Spring ecosystem
- pac4j provides more authentication protocols out-of-the-box
- Spring Security OAuth has better Spring-specific performance optimizations
Use Cases
- Choose pac4j for multi-framework projects or when requiring diverse authentication methods
- Opt for Spring Security OAuth in Spring-based applications for seamless integration
Community and Support
- pac4j has an active community and regular updates
- Spring Security OAuth is in maintenance mode, with new features directed to Spring Security 5.x
Apereo CAS - Identity & Single Sign On for all earthlings and beyond.
Pros of CAS
- More comprehensive authentication and authorization solution
- Supports a wider range of protocols (SAML, OAuth, CAS, etc.)
- Active development and community support
Cons of CAS
- Steeper learning curve due to its complexity
- Requires more configuration and setup compared to Spring Security OAuth
Code Comparison
CAS configuration example:
<bean id="centralAuthenticationService" class="org.apereo.cas.CentralAuthenticationServiceImpl">
<property name="ticketRegistry" ref="ticketRegistry" />
<property name="serviceTicketExpirationPolicy" ref="serviceTicketExpirationPolicy" />
<property name="authenticationManager" ref="authenticationManager" />
</bean>
Spring Security OAuth configuration example:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client-id")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("read", "write");
}
}
Both projects offer robust authentication solutions, but CAS provides a more comprehensive platform for enterprise-level authentication and single sign-on. Spring Security OAuth, while simpler to set up, focuses primarily on OAuth2 implementation. CAS requires more initial configuration but offers greater flexibility and protocol support. The choice between the two depends on specific project requirements and the desired level of complexity.
Java JWT: JSON Web Token for Java and Android
Pros of jjwt
- Lightweight and focused solely on JSON Web Tokens (JWT)
- Easy to use and integrate into existing projects
- Actively maintained and regularly updated
Cons of jjwt
- Limited to JWT functionality, lacking broader OAuth 2.0 support
- May require additional libraries for complete authentication solutions
- Less comprehensive documentation compared to Spring Security OAuth
Code Comparison
spring-security-oauth:
OAuth2RestTemplate template = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(accessTokenRequest));
OAuth2AccessToken token = template.getAccessToken();
jjwt:
String jws = Jwts.builder()
.setSubject("user123")
.signWith(SignatureAlgorithm.HS256, "secret")
.compact();
Summary
jjwt is a specialized library for JWT handling, offering simplicity and ease of use. It's ideal for projects that specifically need JWT functionality. Spring Security OAuth, while no longer actively maintained, provides a more comprehensive OAuth 2.0 solution with broader authentication and authorization capabilities. The choice between the two depends on the project's specific requirements and the desired level of integration with the Spring ecosystem.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
spring-security-oauth is no longer actively maintained by VMware, Inc.
This project has been replaced by the OAuth2 support provided by Spring Security (client and resource server) and Spring Authorization Server.
About
This project provides support for using Spring Security with OAuth (1a) and OAuth2. It provides features for implementing both consumers and providers of these protocols using standard Spring and Spring Security programming models and configuration idioms.
Code of Conduct
This project adheres to the Contributor Covenant code of conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
Getting Started
Download or clone from GIT and then use Maven (3.0.*) and Java (1.6 or better):
$ git clone ...
$ mvn install -P bootstrap
Use the bootstrap
profile only the first time - it enables some
repositories that can't be exposed in the poms by default. You may
find it useful to add this profile to your local settings.xml
.
You need to run Redis to get the build to work. You can install this using homebrew. Without Redis running the build will lots of Jedis connection exceptions
SpringSource ToolSuite users (or Eclipse users with the latest m2eclipse plugin) can import the projects as existing Maven projects.
Spring Security OAuth is released under the terms of the Apache Software License Version 2.0 (see license.txt).
Samples
Samples and integration tests are in a subdirectory. There is a separate README there for orientation and information. Once you have installed the artifacts locally (as per the getting started instructions above) you should be able to
$ cd samples/oauth2/tonr
$ mvn tomcat7:run
and visit the app in your browser at http://localhost:8080/tonr2/ to check that it works. (This is for the OAuth 2.0 sample, for the OAuth 1.0a sample just remove the "2" from the directory path.) Integration tests require slightly different settings for Tomcat so you need to add a profile:
$ cd samples/oauth2/tonr
$ mvn integration-test -P integration
Changelog
Lists of issues addressed per release can be found in github (older releases are in JIRA).
Additional Resources
Contributing to Spring Security OAuth
Here are some ways for you to get involved in the community:
- Get involved with the Spring community on the Spring Community Forums. Please help out on the forum by responding to questions and joining the debate.
- Create github issues for bugs and new features and comment and vote on the ones that you are interested in.
- Github is for social coding: if you want to write code, we encourage contributions through pull requests from forks of this repository. If you want to contribute code this way, please reference a github issue as well covering the specific issue you are addressing.
- Watch for upcoming articles on Spring by subscribing to springframework.org
Before we accept a non-trivial patch or pull request we will need you to sign the contributor's agreement. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge.
- Use the Spring Framework code format conventions. Import
eclipse-code-formatter.xml
from the root of the project if you are using Eclipse. If using IntelliJ, copyspring-intellij-code-style.xml
to~/.IntelliJIdea*/config/codestyles
and select spring-intellij-code-style from Settings -> Code Styles. - Make sure all new .java files have a simple Javadoc class comment with at least an @author tag identifying you, and preferably at least a paragraph on what the class is for.
- Add the ASF license header comment to all new .java files (copy from existing files in the project)
- Add yourself as an @author to the .java files that you modify substantially (more than cosmetic changes).
- Add some Javadocs and, if you change the namespace, some XSD doc elements.
- A few unit tests would help a lot as well - someone has to do it.
- If no-one else is using your branch, please rebase it against the current main (or other target branch in the main project).
Top Related Projects
Spring Security
Spring Authorization Server
Open Source Identity and Access Management For Modern Applications and Services
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...
Apereo CAS - Identity & Single Sign On for all earthlings and beyond.
Java JWT: JSON Web Token for Java and Android
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot