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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Component Tests for Spring Cloud Microservices
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC

Trending

  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Security — Chapter 1

Spring Security — Chapter 1

By 
Vinu Sagar user avatar
Vinu Sagar
·
Mar. 05, 20 · Tutorial
Likes (20)
Comment
Save
Tweet
Share
17.2K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Security is a framework that provides authentication and authorization to Java applications.

Authentication is used to confirm the identity of a user, and authorization checks the privileges and rights a user has that determine what resources and actions they have access to within an application.

Here, we will write a simple REST Controller, a greeting service that wishes you good morning when you go to localhost:7000/morning. We will see how it functions with and without security dependencies.

We will start by creating a spring boot project with the following dependencies.

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>org.springframework.boot</groupId>
3
    <artifactId>spring-boot-starter-security</artifactId>
4
</dependency>
5
<dependency>
6
    <groupId>org.springframework.boot</groupId>
7
    <artifactId>spring-boot-starter-web</artifactId>
8
</dependency>



Now, we will create a simple REST controller that says, "Good Morning."

Java
 




xxxxxxxxxx
1


 
1
@RestController
2
public class GreetingsController {
3
 
          
4
    @GetMapping("/morning")
5
    public String getGreetings() {
6
        return "Good Morning";
7
    }
8
}



Let us update the application.properties file

Plain Text
 




xxxxxxxxxx
1


 
1
server.port=7000



You may also like: OAuth 2.0 Beginner's Guide.

Now, if you run the application and go to localhost:7000/morning, you will be presented with a login screen, as shown below:

Default user sign in

Default user sign in

When you run the application, there will be a security password generated in the console. You can copy it and paste it. The default user name is "user", and the password can be copied from the console.

This will take you to page that says "Good Morning".

Now, if you comment out the security dependency and run the application, you will be taken directly to the page that wishes you "Good Morning".

This gives you a feel for Spring Security can help you secure your application. Now, let's override the default security User Name and Password.

One way of doing this is by creating the application.properties file, as shown below:

Properties files
 




xxxxxxxxxx
1


 
1
server.port=7000
2
spring.security.user.name=hello
3
spring.security.user.password=world



Now, you can run the application. Make sure you uncomment the security dependencies in the POM file.

You will be taken to the same login screen as above, and you can enter "hello" as the username and "world" as the password. You will now be greeted with "Good Morning".

Another way of doing this is by using Java code. Let's comment out the last two lines in the application.properties file, as shown below:

Properties files
 




xxxxxxxxxx
1


 
1
server.port=7000
2
#spring.security.user.name=hello
3
#spring.security.user.password=world



Now, let's write some code. This will require you to Autowire a password encoder. I am using the Bcrypt password encoder. When we try to run the application with @Autowire password encoder, we get an error. We should define a bean for the password encoder. You can also use the NoOpPasswordEncoder, which is deprecated. Have a look at the code below:

Java
 




xxxxxxxxxx
1
23


 
1
@EnableWebSecurity
2
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
3
    @Autowired
4
    private PasswordEncoder passwordEncoder;
5
 
          
6
    @Override
7
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
8
        auth.inMemoryAuthentication()
9
                .withUser("user").
10
//                password("user").
11
//                roles("USER");
12
                password(passwordEncoder.encode( "user")).roles("USER");
13
    }
14
    @Bean
15
    public PasswordEncoder passwordEncoder() {
16
        return new BCryptPasswordEncoder();
17
    }
18
//    @Bean
19
//    public PasswordEncoder passwordEncoder() {
20
//        return NoOpPasswordEncoder.getInstance();
21
//    }
22
}
23
 
          



When using the NoOpPasswordEncoder you don't require an encoder for the password.

Now, by running this application, you will be taken to the same login screen where you can enter the username as "user" and the password as "user". You will be greeted with "Good Morning".

You can find the full source code at https://github.com/gudpick/security-demo.

You can find the video tutorial at https://youtu.be/e-9rPnlHWL8.



Further Reading

  • Spring Security Authentication.
Spring Security Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Component Tests for Spring Cloud Microservices
  • 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!