Spring Security is an essential tool to ensure the protection of our applications. It's a concept that provides security for our web applications or REST APIs using Spring Boot. It's all about implementing robust security measures for our applications.
In the context of web application security, two critical aspects are authentication and authorization. These are particularly important when we're discussing security.
I. What is Authentication?
Authentication is a key- process that involves gaining access to an application. This is accomplished by verifying the user's credentials. we can implement this by using username and password.
II. What is Authorization?
Authorization is indeed the mechanism that determines user access to resources. It's the process that decides whether a user has the necessary permissions to access a particular resource or not.
In spring boot, we can add the below dependency on pom.xml for to secure our application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.Basic Authentication:
when we add above dependency in pom.xml the by default spring will generate basic authentication for our application i.e. Spring will generate one random password and by default username is user when we access our application by URL then we get a login form to access our application.
checkout code here https://github.com/NithinManupuri/Spring-Security.git
By default, spring provides the username and password, we can override our credentials by configuring the details in application. Properties file.
spring.security.username=username
spring.security.user.password=password
we can customize security Configuration base on our request to our application by filtering the URL's.
package in.spring.config;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityFiltering {
@Bean
public SecurityFilterChain pathFiltering(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize)->authorize.
requestMatchers("/hello","/swagger-ui.html").permitAll()
.anyRequest().
authenticated())
.httpBasic(withDefaults()).formLogin(withDefaults());
return http.build();
}
}
2.Spring Security-InMemoryAuthentication:
It is to provide security to your application directly within the program. This is where the user credentials are stored directly in the application code. While this method might not be suitable for production use due to security considerations, it serves for learning.
3.Spring-JDBC Authentication:
Spring JDBC Authentication that manages authentication and authorization requests by fetching and verifying data to grant access.
checkout here-
Implementing the Spring JDBC Authentication
step-1) Create a table in your database and insert the data into the table, In place of password inserts the encrypted password.
CREATE TABLE Users (
username VARCHAR(50) NOT NULL,
password VARCHAR(120) NOT NULL,
enabled TINYINT(1) NOT NULL,
PRIMARY KEY (username)
);
CREATE TABLE authorities (
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
KEY username (username),
CONSTRAINT authorities_fk FOREIGN KEY (username)
REFERENCES users (username)
);
step-2) Create a Spring Boot application and add below dependency.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Step-4) Create a Rest Controller class.
package in.spring.rest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AppRestController {
@GetMapping("/user")
public String user(){
return"Hello-User";
}
@GetMapping("/admin")
public String admin(){
return"Hello-Admin";
}
@GetMapping("/welcome")
public String welcome(){
return"Hello-welcome";
}
}
step-5) Create a Configuration Class to present Authentication.
package in.spring.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class AppConfig {
private static final String ADMIN = "Admin";
private static final String USER = "user";
@Autowired
private DataSource datasource;
@Autowired
public void jdbcAuth(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(datasource).passwordEncoder(new BCryptPasswordEncoder())
.usersByUsernameQuery("select username,password,enabled from users where username=?")
.usersByUsernameQuery("select username,authority from authorities where username=?");
}
@Bean
public SecurityFilterChain acces(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((req) -> req.requestMatchers("/admin").hasRole(ADMIN).requestMatchers("/user")
.hasAnyRole(ADMIN, USER).requestMatchers("/welcome").permitAll().anyRequest().authenticated()).formLogin();
return http.build();
}
}
4.Oauth 2.0:
It stands for "Open Authorization" which means to access a web application which is hosted by other application on their behalf.
Example when we visit Myntra their will a option to login through google.
Go to GitHub ->settings->developer settings.
spring:
security:
oauth2:
client:
registration:
github:
clientId: <client id>
clientSecret: <Client secret>
5.JWT:
Jwt stands for JSON web token, which claims a secure communication between two parties.
It is stateless it doesn't maintain the previous request data.
Token consist of headers, payload, signature-> check out here- JSON Web Tokens - jwt.io