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
Newsletter
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
  • Hardening MCP Gateways: Mitigating July 28 Security Risks in Java Applications
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways

Trending

  • The Three Tiers of Agentic Incident Response: When to Trust AI Autonomy
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • YAGNI in the Age of AI Coding
  • How to Migrate From LangChainGo to Genkit Go

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Generating OAuth Tokens Part 1

Generating OAuth Tokens Part 1

By 
Vinu Sagar
·
May. 18, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
  • Hardening MCP Gateways: Mitigating July 28 Security Risks in Java Applications
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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