Security
Security
Security
Assignment
=============
2) Develop Consumer app (Rest Client) to access secured rest api using Rest
Template & WebClient.
=================
Spring Security
=================
-> To protect our application & application data we need to implement security
logic
-> Spring Security concept we can use to secure our web applications / REST APIs
-> To secure our spring boot application we need to add below starter in pom.xml
file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Note: When we add this dependency in pom.xml file then by default our application
will be secured with basic authentication. It will generate random password to
access our application.
Username : user
-> When we access our application url in browser then it will display "Login Form"
to authenticate our request.
-> To access secured REST API from postman, we need to set Auth values in POSTMAN
to send the request
=====================================================
How to override Spring Security Default Credentials
=====================================================
spring.security.user.name=ashokit
spring.security.user.password=ashokit@123
-> After configuring credentials like above, we need to give above credentials to
access our application / api.
=====================================
How to secure specific URL Patterns
=====================================
-> When we add 'security-starter' in pom.xml then it will apply security filter for
all the HTTP methods of our application.
-> But in reality we need to secure only few methods not all methods in our
application.
##For Example##
@Configuration
@EnableWebSecurity
public class SecurityConfigurer {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception {
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/contact", "/swagger-
ui.html").permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults())
.formLogin(withDefaults());
return http.build();
}
}
==========================================
Spring Security In-Memory Authentication
==========================================
-> In Memory Authentication means storing user credentials in the program for
Authentication Purpose.
@Bean
public InMemoryUserDetailsManager inMemoryUsers() {
==============================================
Spring Boot Security with JDBC Authentication
==============================================
=> JDBC Authentication is used to fetch Db table data for User authentication
purpose
a) web-starter
b) security-starter
c) data-jdbc
d) mysql-connector
e) lombok
f) devtools
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: AshokIT@123
url: jdbc:mysql://localhost:3306/sbms66
username: ashokit
jpa:
show-sql: true
@RestController
public class UserRestController {
@GetMapping(value = "/admin")
public String admin() {
return "<h3>Welcome Admin :)</h3>";
}
@GetMapping(value = "/user")
public String user() {
return "<h3>Hello User :)</h3>";
}
@GetMapping(value = "/")
public String welcome() {
return "<h3>Welcome :)</h3>";
}
Step-5) Create Security Configuration class like below with Jdbc Authentication
Manager
package in.ashokit;
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.Authenticati
onManagerBuilder;
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 SecurityConfiguration {
@Autowired
private DataSource dataSource;
@Autowired
public void authManager(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(new BCryptPasswordEncoder())
.usersByUsernameQuery("select username,password,enabled from
users where username=?")
.authoritiesByUsernameQuery("select username,authority from
authorities where username=?");
}
@Bean
public SecurityFilterChain securityConfig(HttpSecurity http) throws Exception
{
return http.build();
}
=======================================================
How to work with UserDetailsService in Spring Security
=======================================================
=> This is used to load User record for Authentication purpose in Spring Security.
=> We can implement UserDetailsService interface and we can write the logic to
retrieve User record based on given username for Authentication purpose.
==============================================
Login and Registration using Spring Security
==============================================
a) web-starter
b) data-jpa-starter
c) mysql
d) security-starter
e) devtools
@Repository
public interface CustomerRepo extends CrudRepository<Customer, Integer> {
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private CustomerRepo crepo;
@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
Customer c = crepo.findByUname(username);
return new User(c.getUname(), c.getPwd(), Collections.emptyList());
}
}
@Configuration
@EnableWebSecurity
public class AppSecurityConfig {
@Autowired
private MyUserDetailsService userDtlsSvc;
@Bean
public PasswordEncoder pwdEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider=
new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDtlsSvc);
authenticationProvider.setPasswordEncoder(pwdEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration
config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityConfig(HttpSecurity http) throws Exception
{
return http.csrf().disable()
.authorizeHttpRequests()
.requestMatchers("/register", "/login").permitAll()
.and()
.build();
}
}
@RestController
public class CustomerRestController {
@Autowired
private CustomerRepo crepo;
@Autowired
private PasswordEncoder pwdEncoder;
@Autowired
private AuthenticationManager authManager;
@PostMapping("/login")
public ResponseEntity<String> loginCheck(@RequestBody Customer c) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(c.getUname(),
c.getPwd());
try {
Authentication authenticate = authManager.authenticate(token);
if (authenticate.isAuthenticated()) {
return new ResponseEntity<>("Welcome To Ashok IT",
HttpStatus.OK);
}
} catch (Exception e) {
//logger
}
@PostMapping("/register")
public String registerCustomer(@RequestBody Customer customer) {
// duplicate check
crepo.save(customer);
##############
OAuth 2.0
##############
a) web-starter
b) security-starter
c) oauth-client
### 3) Configure GitHub OAuth App client id & client secret in application.yml file
like below
spring:
security:
oauth2:
client:
registration:
github:
clientId:
clientSecret:
@RestController
public class WelcomeRestController {
@GetMapping("/")
public String welcome() {
return "Welcome to Ashok IT";
}
}
Assignment : Spring Boot with oAuth using google account. Get username also from
google and display that in response.
#########################
Spring Boot with JWT
########################
-> JSON Web Tokens are an open, industry standard RFC 7519 method for representing
claims securely between two parties.
token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv
aG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
1) Header
2) Payload
3) Signature
Note: JWT 3 parts will be seperated by using dot(.)
- generateToken(String uname)
- validateToken(String uname)
3) Customize SecurityFilterChain
============================
Authorization Token Format
============================
Key = Authorization
Value = Bearer <token>
================================
Microservices with JWT Security
===============================
=> Auth-Service contains functionality for user registration and user login with
MySQL DB.
=> If user login successfully then auth-service will generate JWT token and will
send it as response to user.
Note: In API-Gateway we have added routings for our microservices along with
Filter.
=> When we access any microservice url through api-gateway then api-gateway will
execute filter to validate the token. If token is valid then only api-gateway will
route the request to particular microservice. If token is invalid then api-gateway
will throw Exception.
=========
Summary
==========
1) Monolithic Architecture
2) Drawback with Monolith
3) Microservices Introduction
4) Microservices Advantages
5) Challenges with Microservices
6) Microservices Architecture
7) Service Registry (Eureka)
8) Admin Server (codecentric)
9) Zipkin Server
10) Backend APIs
11) FeignClient
12) Load Balancing
13) Api Gateway
14) Config Server
15) Circuit Breaker (Resillence4J)
16) Redis Cache