
Play Store Application link β Spring Boot in 13 steps – App on Google Play
Github project link – https://github.com/kuldeep101990/Spring-Boot-Security
Step 1: Setting Up a Spring Boot Project
Using Spring Initializr
- Go to https://start.spring.io/.
- Fill in the details:
- Project: Maven
- Language: Java
- Spring Boot: 3.x.x
- Dependencies: Spring Web, Spring Security
- Click Generate, and extract the downloaded ZIP file.
Import into IDE
- Open your IDE (e.g., IntelliJ or Eclipse).
- Import the extracted project as a Maven project.
Step 2: Configuring Basic Authentication
Spring Boot makes it simple to enable basic authentication with properties.
Add Basic Authentication in application.properties
spring.security.user.name=admin
spring.security.user.password=admin123
Create a REST Controller
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SecurityController {
@GetMapping("/public")
public String publicEndpoint() {
return "This is a public endpoint";
}
@GetMapping("/secured")
public String securedEndpoint() {
return "This is a secured endpoint";
}
}
When accessing /secured
, the browser will prompt for the username and password configured in application.properties
.
Step 3: Role-Based Access Control
Configure Custom Roles
Add the following in SecurityConfig
:
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public").permitAll()
.requestMatchers("/secured").hasRole("USER")
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user123")
.roles("USER")
.build();
UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("admin123")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
Test Role-Based Access
/public
: Accessible by anyone./secured
: Accessible only by users with theUSER
role.
Step 4: Securing REST APIs with JWT
Add Dependencies
Include the following in pom.xml
:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
Create a JWT Utility Class
package com.example.demo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
private static final String SECRET_KEY = "mysecretkey";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public String validateToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
}
Add a Login Endpoint
package com.example.demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class JwtController {
private final JwtUtil jwtUtil = new JwtUtil();
@PostMapping("/login")
public String login(@RequestParam String username) {
return jwtUtil.generateToken(username);
}
}
Step 5: Advanced Security with OAuth2
Add OAuth2 Dependency
Include the following in pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Configure OAuth2 Login
Add the following in application.properties
:
spring.security.oauth2.client.registration.google.client-id=<your-client-id>
spring.security.oauth2.client.registration.google.client-secret=<your-client-secret>
spring.security.oauth2.client.registration.google.scope=profile,email
spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
Conclusion
In this guide, we:
- Configured basic authentication with Spring Boot.
- Implemented role-based access control.
- Secured REST APIs using JWT.
- Explored advanced security with OAuth2.
An impressive share, I just given this onto a colleague who was doing a bit of evaluation on this. And he in fact purchased me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If potential, as you become expertise, would you thoughts updating your blog with more particulars? It’s highly useful for me. Massive thumb up for this weblog post!
Excellent beat ! I wish to apprentice while you amend your site, how can i subscribe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea
Thanks for the new stuff you have unveiled in your blog post. One thing I want to discuss is that FSBO interactions are built after some time. By bringing out yourself to the owners the first few days their FSBO can be announced, ahead of masses get started calling on Mon, you build a good interconnection. By sending them instruments, educational supplies, free reports, and forms, you become a great ally. By taking a personal interest in them in addition to their predicament, you produce a solid network that, many times, pays off when the owners opt with a broker they know and also trust – preferably you.
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?
Definitely believe that which you said. Your favourite reason seemed to be at the web the simplest thing to take into accout of. I say to you, I certainly get annoyed whilst other people consider worries that they just don’t understand about. You controlled to hit the nail upon the highest as smartly as defined out the entire thing with no need side effect , folks could take a signal. Will likely be again to get more. Thanks
Sweet blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it
I used to be recommended this website via my cousin. I’m no longer sure whether this put up is written by him as no one else recognise such special about my problem. You’re incredible! Thank you!
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?
hi!,I really like your writing so a lot! percentage we keep up a correspondence extra approximately your post on AOL? I need a specialist on this area to solve my problem. May be that’s you! Looking forward to peer you.
I am extremely inspired together with your writing skills and also with the layout for your blog. Is that this a paid subject or did you modify it yourself? Anyway stay up the nice quality writing, it is uncommon to peer a nice blog like this one today..
Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your webpage? My blog site is in the exact same area of interest as yours and my users would truly benefit from a lot of the information you present here. Please let me know if this alright with you. Regards!
As I web-site possessor I believe the content matter here is rattling magnificent , appreciate it for your efforts. You should keep it up forever! Best of luck.
Hey, you used to write great, but the last few posts have been kinda boring?I miss your great writings. Past several posts are just a little out of track! come on!
Hi would you mind stating which blog platform you’re working with? I’m going to start my own blog in the near future but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something unique. P.S My apologies for being off-topic but I had to ask!
Super-Duper website! I am loving it!! Will be back later to read some more. I am bookmarking your feeds also.
This is really interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your site in my social networks!
Hey! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa? My site addresses a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you are interested feel free to send me an e-mail. I look forward to hearing from you! Wonderful blog by the way!
Would you be interested in exchanging links?
Thanks for the tips shared on your blog. Something also important I would like to say is that fat reduction is not exactly about going on a celebrity diet and trying to reduce as much weight as you can in a few months. The most effective way to lose weight naturally is by acquiring it slowly and gradually and following some basic suggestions which can allow you to make the most through your attempt to lose fat. You may realize and already be following many of these tips, nevertheless reinforcing expertise never affects.
Amazing blog! Do you have any helpful hints for aspiring writers?
I’m planning to start my own blog soon but I’m a little lost on everything.
Would you advise starting with a free platform like WordPress or
go for a paid option? There are so many choices out there
that I’m totally confused .. Any suggestions?
Many thanks!
my website: nordvpn coupons inspiresensation
fantastic post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I’m sure, you have a huge readers’ base already!
My brother recommended I might like this website. He was totally right. This put up truly made my day. You can not believe just how much time I had spent for this information! Thank you!
The very core of your writing while appearing reasonable at first, did not really sit properly with me personally after some time. Someplace throughout the paragraphs you actually were able to make me a believer but only for a while. I nevertheless have got a problem with your jumps in assumptions and one might do nicely to fill in those breaks. When you can accomplish that, I would certainly end up being fascinated.
Along with almost everything that seems to be building within this specific subject material, many of your points of view happen to be relatively stimulating. Nevertheless, I am sorry, but I do not give credence to your entire plan, all be it exciting none the less. It would seem to everybody that your remarks are actually not completely validated and in fact you are yourself not really thoroughly certain of your assertion. In any event I did take pleasure in looking at it.
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?
I simply wanted to send a simple word in order to appreciate you for the stunning guides you are posting at this website. My prolonged internet search has finally been rewarded with good details to share with my classmates and friends. I ‘d declare that most of us readers actually are quite endowed to be in a very good community with many wonderful individuals with very beneficial points. I feel extremely fortunate to have seen the web page and look forward to some more awesome times reading here. Thanks once again for all the details.
Thanks for your personal marvelous posting! I genuinely enjoyed reading it, you will be a great author.I will be sure to bookmark your blog and will come back down the road. I want to encourage continue your great writing, have a nice holiday weekend!
Another thing I have really noticed is the fact for many people, poor credit is the response to circumstances outside of their control. For instance they may be really saddled having an illness and because of this they have high bills going to collections. It might be due to a job loss or perhaps the inability to do the job. Sometimes separation and divorce can send the budget in the wrong direction. Thanks sharing your thinking on this blog site.
Hello there! Do you use Twitter? I’d like to follow you if that would be okay. I’m absolutely enjoying your blog and look forward to new posts.
Hey! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!
Undeniably believe that which you said. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks
This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your web site in my social networks!
Hello are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated!
Another issue is that video games are usually serious naturally with the main focus on knowing things rather than leisure. Although, we have an entertainment element to keep the kids engaged, just about every game is usually designed to develop a specific skill set or programs, such as math concepts or science. Thanks for your post.
Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My blog is in the exact same area of interest as yours and my users would truly benefit from some of the information you provide here. Please let me know if this ok with you. Cheers!