#SpringSecurity Part 2 : Creating a simple Spring security project (Basic Authentication)

Himaanshu Shukla
3 min readDec 4, 2021

--

In the Part 1 of #SpringSecurity Part 1, I explained the difference between Authentication and Authorization. Now let’s see how can we implement basic authentication in Spring.

Let’s create a Spring Starter Project from STS, as of now this project has only Spring Web dependency.

Create controller classes AuthenticationController.java and UserController.java inside it.

UserController.java
AuthenticationController.java

Since we kept the controllers in ‘com.greekykhs.controller’ package, add the ComponentScan in Main class.

SpringSecurity21Application.java

Once we run our Spring boot project, we can access below get rest webservices directly.

GIT URL: spring-security-21

Now let’s say we don’t want anyone to directly access these services, instead we want our users to enter user name and password. For this we need to make a small modification in pom.xml and add ‘spring-boot-starter-security’ dependency.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Now, if you restart the spring boot project after adding this dependency and try to access any web-service you will get a prompt to enter user name and password ( form-based authentication), this is the default behavior for spring security.

The user name, by default is ‘user’ and we can get the password from the console for our application. When you check the console you will see a user-generated security password.

Let’s say you do not want to use autogenerated password and username as ‘user’, in that case we can configure it via application.properties.

spring.security.user.name=greekykhs
spring.security.user.password=pass12345

When you add above two lines in the application.properties and restart the application, you won’t see ‘generated security password’ on the console. And you can access the web-services with user name as ‘greekykhs’ and password as ‘pass12345’.

Did you know you could give up to 50 claps?
Yes, 50 claps, isn’t it awesome. If you feel my posts are interesting or helpful to you, please do press the 👏 clap button and share/ follow, help others find this story too. Also, feel free to leave a comment below.

If you enjoyed reading my blogs, I’d appreciate it if you’d buy me a coffee

Keep learning and growing!
- Himanshu Shukla..

--

--

Himaanshu Shukla

Software Engineer | Certified Scrum Master | Angel Therapy Practitioner| Light Worker| Empath | Buy me a coffee https://ko-fi.com/greekykhs |Blogger