DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Composing Custom Annotations in Spring
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  1. DZone
  2. Coding
  3. Java
  4. Java Spring OAuth2 and Basic Auth Support

Java Spring OAuth2 and Basic Auth Support

The goal of the post is to share an idea of how can we provide the basic authentication and OAuth 2 authentication for the APIs.

By 
Kanifnath Gaikwad user avatar
Kanifnath Gaikwad
·
Oct. 07, 20 · Analysis
Likes (4)
Comment
Save
Tweet
Share
19.5K Views

Join the DZone community and get the full member experience.

Join For Free

The goal of the post is to share an idea how can we provide the basic authentication and OAuth 2 authentication for the APIs, meaning with new technologies we need to support the OAuth2 for new clients, but at the same time we still need to support the basic authentication way of securing the APIs maybe for time for existing API Users.

Basic Auth

In general, in basic auth clients call API keeping username:password in the Authorization header for the APIs. By standard basic auth annotation, the username:password will be Base 64 encoded string.

HTTP
 




xxxxxxxxxx
1


 
1
GET /book/{id} HTTP/1.1
2
Host: mybooks.com
3
Content-Type: application/json
4
Authorization: Basic MzMzOjQ0NA==



OAuth 2.0

Now for the new clients, you would want to keep the API the same and change the authorization part of the API, maybe the OAuth2 token in the authorization header instead of the basic auth header, something like.

HTTP
 




xxxxxxxxxx
1


 
1
GET /book/{id} HTTP/1.1
2
Host: mybooks.com
3
Content-Type: application/json
4
Authorization: Bearer eyJraWQiOiJRWk1WZ01sUGJzVkhuYk9pOGVXMWlDazVES1VGT...



With this you want your Spring Java Rest APIs to have support both authentication, depending on the client header type let the application decide the route to take for authentication.

For this to work, we will have to understand the Spring security a bit. In the Spring security, you will find the filter chain the gets executed upon any request from the client, which could be requested from web browsers, mobile clients, or Rest clients.

For the request handling, we need to configure the WebSecurityConfigureAdapter in the Spring configuration, like

Java
 




x


 
1
 @Override
2
        protected void configure(HttpSecurity http) throws Exception {
3
            http
4
                    .antMatcher("/**/book/**")
5
                    .authorizeRequests()
6
                    .antMatchers("/**/book/**").authenticated();
7

          
8
        }



The above code tells the Spring that any request for book APIs should be authenticated, internally it's going to check for SecurityContext information when serving these requests.

Now, for Spring basic authentication we generally configure the daoAuthentication provider with an overridden method. So whenever the spring security chain executed the Springs basic auth filter will be called and internally it calls the dao provider for authentication. It's a lengthy topic to cover in one post, I will cover that up in a separate post. but, bottom line is that you need to have the dao provider along with the basic authentication filter.

Java
 




x


 
1
 @Override
2
        protected void configure(HttpSecurity http) throws Exception {
3
            http
4
                    .antMatcher("/**/book/**")
5
                    .authorizeRequests()
6
                    .antMatchers("/**/book/**").authenticated()
7
                    .and().authenticationProvider(bookDaoAuthenticationProvider)
8
                    .httpBasic().realmName("MyBooks.Com")
9
                    .csrf().disable();
10
        }



So for our example we have bookDaoAuthenticationProvider, with HTTP basic on it. All basic auth requests will be served from Spring's BasicAuthenticationFilter if they have the Basic keyword starts in the  Authorization header, that's Spring's internal logic.

For OAuth2 requests, we can use the AbstractPreAuthenticatedProcessingFilter, as the tokens would be pre-validated by the OAuth2 token servers and it's just needed the verification from the Spring application now. Tokens are generally JWT tokens.

We can configure the security to handle requests like

Java
 




xxxxxxxxxx
1
12


 
1
  @Override
2
        protected void configure(HttpSecurity http) throws Exception {
3
            http
4
                    .antMatcher("/**/book/**")
5
                    .authorizeRequests()
6
                    .antMatchers("/**/book/**").authenticated()
7
                    .and().authenticationProvider(booksDaoAuthenticationProvider)
8
                    .httpBasic().realmName("MyBooks.Com")
9
                    .and()
10
                    .addFilter(booksJwtPreAuthFilter)
11
                    .csrf().disable();
12
        }



The booksJwtPreAuthFilter can be configured like —

Java
 




xxxxxxxxxx
1
12


 
1
public class BookJwtPreAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
2
    @Override
3
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
4
            throws IOException, ServletException {
5
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
6
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
7
        //Validate Accees Tokens
8
        chain.doFilter(request, response);
9
    }
10

          
11
}



Keep in mind the API request Authorization header is important here. If it has a Basic keyword it would be served by BasicAuthFilter in the chain and SecurityContext would be created. Now AbstractPreAuthenticatedProcessingFilter filters would be only invoked if the security context has not been created yet, that's the whole point of this logic.

Hope this gives a good idea about the Spring Rest API authentication for Basic Auth and For OAuth2 for that matter any other security protocol as well.

authentication Spring Security Spring Framework Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Composing Custom Annotations in Spring
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!