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

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

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

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

  • 10 Ways To Keep Your Java Application Safe and Secure
  • Kafka Security With SASL and ACL
  • Secure Communication with Token-based RSocket
  • MuleSoft OAuth 2.0 Provider: Password Grant Type

Trending

  • Internal Developer Portals: Modern DevOps's Missing Piece
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  1. DZone
  2. Coding
  3. Java
  4. Generating OAuth Tokens Part 1

Generating OAuth Tokens Part 1

By 
Vinu Sagar user avatar
Vinu Sagar
·
May. 18, 20 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
14.5K Views

Join the DZone community and get the full member experience.

Join For Free

We will talk about how to generate OAuth tokens. When using OAuth tokens, passwords are not shared between services. Instead, tokens are used for authentication. Here, we will create a basic authorization server that creates tokens given the username and password.

Let us create a new class that extends AuthorizationServerConfigurerAdapter. We can annotate it with @Configuration to tell it is a configuration class and has one or more @Bean methods. To enable the authorization server, we will use @EnableAuthorizationServer.

Java
xxxxxxxxxx
1
 
1
@Configuration
2
@EnableAuthorizationServer
3
public class AuthServer extends AuthorizationServerConfigurerAdapter


Now, let us create a bean for the password encoder. We can use the BcryptPasswordEncoder for encoding the passwords.

Java
xxxxxxxxxx
1
 
1
@Bean
2
public PasswordEncoder passwordEncoder() {
3
    return  new BCryptPasswordEncoder();
4
}


We will override the configure methods as below. There are three configure methods. We will do it as below. Here, we can configure grant types, passwords, refresh token validity, access token validity, scopes

Java
xxxxxxxxxx
1
 
1
@Override
2
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
3
    clients.inMemory().withClient("client")
4
            .secret(passwordEncoder.encode(("secret")))
5
            .authorizedGrantTypes("password")
6
            .scopes("webclient","mobileclient");
7
}


Grant Types:

  • Authorization code grant.
  • Implicit grant.
  • Resource owner credentials grant.
  • Client credentials grant.
  • Refresh token grant.

Scope

Scopes limits the application's access to user's accounts. It can have one or more scopes.

Java
xxxxxxxxxx
1
 
1
@Override
2
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
3
    endpoints.authenticationManager(authenticationManagerBean);
4
}


Let us now create on more class WebSecurity, which extends WebSecurityConfigurerAdapter and annotate it with @Configuration and @EnableWebSecurity

Java
xxxxxxxxxx
1
 
1
@Configuration
2
@EnableWebSecurity
3
public class WebSecurity extends WebSecurityConfigurerAdapter 


Let us override the configure method

Java
xxxxxxxxxx
1
 
1
@Override
2
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
3
    auth.inMemoryAuthentication().withUser("user").password(passwordEncoder.encode("user")).roles("USER");
4
}


Here, I am having username as "user" and password as "user", and roles I've specified as "USER".

Now, let me create a bean. This is required in the newer versions. 

Java
xxxxxxxxxx
1
 
1
@Override
2
@Bean
3
public AuthenticationManager authenticationManagerBean() throws Exception {
4
    return super.authenticationManagerBean();
5
}


Now, a very minimal authorization server is ready.  Please see the classes below:

AuthServer.java

Java
xxxxxxxxxx
1
25
 
1
import org.springframework.beans.factory.annotation.Autowired;
2
import org.springframework.context.annotation.Bean;
3
import org.springframework.context.annotation.Configuration;
4
import org.springframework.security.authentication.AuthenticationManager;
5
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
7
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
8
import org.springframework.security.crypto.password.PasswordEncoder;
9
10
@Configuration
11
@EnableWebSecurity
12
public class WebSecurity extends WebSecurityConfigurerAdapter {
13
    @Autowired
14
    private PasswordEncoder passwordEncoder;
15
    @Override
16
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
17
        auth.inMemoryAuthentication().withUser("user").password(passwordEncoder.encode("user")).roles("USER");
18
    }
19
20
    @Override
21
    @Bean
22
    public AuthenticationManager authenticationManagerBean() throws Exception {
23
        return super.authenticationManagerBean();
24
    }
25
}


WebSecurity.java

Java
xxxxxxxxxx
1
25
 
1
import org.springframework.beans.factory.annotation.Autowired;
2
import org.springframework.context.annotation.Bean;
3
import org.springframework.context.annotation.Configuration;
4
import org.springframework.security.authentication.AuthenticationManager;
5
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
7
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
8
import org.springframework.security.crypto.password.PasswordEncoder;
9
10
@Configuration
11
@EnableWebSecurity
12
public class WebSecurity extends WebSecurityConfigurerAdapter {
13
    @Autowired
14
    private PasswordEncoder passwordEncoder;
15
    @Override
16
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
17
        auth.inMemoryAuthentication().withUser("user").password(passwordEncoder.encode("user")).roles("USER");
18
    }
19
20
    @Override
21
    @Bean
22
    public AuthenticationManager authenticationManagerBean() throws Exception {
23
        return super.authenticationManagerBean();
24
    }
25
}


Please find the source code at https://github.com/gudpick/oauth-demo/tree/oauth-starter

Please find video tutorials at:


authentication security Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • 10 Ways To Keep Your Java Application Safe and Secure
  • Kafka Security With SASL and ACL
  • Secure Communication with Token-based RSocket
  • MuleSoft OAuth 2.0 Provider: Password Grant Type

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!