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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 10 Ways To Keep Your Java Application Safe and Secure
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Context-Aware Authorization for AI Agents
  • Enterprise Java Applications: A Practical Guide to Securing Enterprise Applications with a Risk-Driven Architecture

Trending

  • Securing the AI Host: Spring AI MCP Server Communication With API Keys
  • DevOps and Platform Engineering Readiness Checklist: Everything Needed for a Scalable, Secure, High-Velocity Delivery Platform
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka
  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.8K 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
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Context-Aware Authorization for AI Agents
  • Enterprise Java Applications: A Practical Guide to Securing Enterprise Applications with a Risk-Driven Architecture

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook