0% found this document useful (0 votes)
24 views

Session04 - Spring Security

bai 4 spring

Uploaded by

k42.dkhao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Session04 - Spring Security

bai 4 spring

Uploaded by

k42.dkhao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Session 04: Spring Security

Objectives
• Authentication and Authorization
• JSON Web Token
• Spring Security

R2S Academy - Internal Use 2


Authentication and Authorization (1)
Introduction
• Authentication is the process used to authenticate user’s identity, whereas
authorization is a way to provide permission to the user to access a
particular resource.

R2S Academy - Internal Use 3


Authentication and Authorization (2)
Difference between
• Example
Authentication Authorization

Employees in a company are required to After an employee successfully authenticates,


authenticate through the network before the system determines what information the
accessing their company email. employees are allowed to access.

• Techniques
Authentication Authorization
1/ Password-Based Authentication JSON web token (JWT)
2/ Single Sign On (SSO)

R2S Academy - Internal Use 4


Authentication and Authorization (3)
Example
• Consider a scenario where a user wants to access his Gmail inbox page. For this the user
will be sending HTTP requests to Gmail server and in response will expect the response
from Gmail Server.

R2S Academy - Internal Use 5


Authentication and Authorization (4)
Example
• The steps will be as follows-
- The user will send a http request to Gmail server with url /login.
Along with this request the user will also be sending the username
and password for authentication.
- The Gmail server will authenticate this request if it is successful it
will return the Gmail inbox page as response to the user.
- Now suppose the user wants to access his sent mail page, so
he will again send a request to the Gmail server with url /
sentmails. This time he will not be sending the username and
password since he user has already authenticated himself in
the first request.
- The user expects Gmail to return the sent mail page. However
this will not be the case. The Gmail server will not return the
sent mail page but will instead not recognize the user.
Reference: https://www.javainuse.com/webseries/spring-security-jwt/chap1
R2S Academy - Internal Use 6
Authentication and Authorization (5)
Example
• Using Session Management for Authorization

Drawbacks:
• During each validation the Gmail server needs to fetch the information corresponding to it.
• Not suitable for micro services architecture involving multiple API's and servers
R2S Academy - Internal Use 7
Authentication and Authorization (6)
Example
• Using JWT for Authorization

JWT

R2S Academy - Internal Use 8


JSON Web Token (1)
What is JWT?
• A JSON web token (JWT) is JSON Object which is used to securely transfer
information over the web (between two parties).
• JWT defines the structure of information we are sending from one party to
the another. The token is mainly composed of header, payload, signature
<header>.<payload>.<signature>
• Structure of a JWT:
• Header: Contains the token type (JWT) and signing algorithm (e.g., HS256)
• Payload: Contains claims, which are pieces of information about the user (e.g.,
username, roles).
• Signature: Generated by hashing the header and payload with a secret key server-
side. This ensures the token's integrity and prevents modification.
R2S Academy - Internal Use 9
JSON Web Token (2)
Example
• Header: Contains the token type (JWT)
and signing algorithm (e.g., HS256)
• Payload: Contains claims, which are
pieces of information about the user
(e.g., username, roles).
• Signature: Generated by hashing the
header and payload with a secret key
server-side. This ensures the token's
integrity and prevents modification.

R2S Academy - Internal Use 10


Spring Security (1)
What is Spring Security
• Spring security provides authentication and authorization to our
application using simple servlet filters
• Example: Unauthorized

R2S Academy - Internal Use 11


Spring Security (2)
What is Spring Security
• Spring security provides authentication and authorization to our
application using simple servlet filters
• Example: Authorized

R2S Academy - Internal Use 12


Spring Security (3)
Authentication Architecture

R2S Academy - Internal Use 13


Spring Security (4)
Authentication Architecture
For handling ilter • AuthenticationFilter:
- When an HTTP request is received by the application, it passes
through this filter chain, and the AuthenticationFilter is responsible
for handling authentication-related requests
- It provides various implementations of AuthenticationFilter, each
tailored to handle different authentication mechanisms and
protocols. For example:
• UsernamePasswordAuthenticationFilter: This filter is
commonly used for processing form-based login requests where
users provide their username and password.
• …

Request

R2S Academy - Internal Use 14


f
Spring Security (5)
Authentication Architecture
For handling ilter
• AuthenticationFilter:

Authenticated
user?

R2S Academy - Internal Use 15


f
Spring Security (6)
Authentication Architecture
For handling ilter
• AuthenticationFilter:

Authorize Http Requests:


• Permit all
• Authenticated Secured? Secured POST /api/user/login
=> Controller
• hasRole
R2S Academy - Internal Use Securing GET /error 16
f
Spring Security (7)
Authentication Architecture
For handling login
Secured? Secured POST /api/user/login => Controller

R2S Academy - Internal Use 17


Spring Security (8)
Authentication Architecture
For handling login

R2S Academy - Internal Use 18


Spring Security (9)
Authentication Architecture
For handling login

R2S Academy - Internal Use 19


Spring Security (10)
Authentication Architecture
For handling login
• UserDetails:
- isAccountNonExpired(): checks if the user’s account has
expired.
- isAccountNonLocked(): checks if the user’s account is
locked.
- isCredentialsNonExpired(): checks if the user’s
credentials (password) have expired.
- isEnabled(): checks if the user’s account is enabled.
- getAuthorities(): returns the authorities granted to the
user.

R2S Academy - Internal Use 20


Spring Security (11)
Authentication Architecture
For handling login
• UserDetailsService:
- When a user attempts to authenticate, Spring Security
needs to retrieve the user's details from a database in
order to perform authentication checks. It has a single
method:
public interface UserDetailsService {
UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException;
}
- It returns an implementation of the UserDetails
interface (User), which typically contains information
such as the user's username, password (or password
hash), and authorities (roles).
R2S Academy - Internal Use 21
Spring Security (12)
Authentication Architecture
For handling login
• PasswordEncoder:
- It provides a way to hash passwords before storing them
in a database. It has a single method
public interface PasswordEncoder {
String encode(CharSequence rawPassword);
}
- When configuring Spring Security in an application,
developers typically specify a PasswordEncoder bean to
be used for encoding passwords.

R2S Academy - Internal Use 22


Spring Security (13)
Implement
• Add Dependencies: <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
• Configure WebSecurity:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// Disable CSRF
http.csrf(AbstractHttpConfigurer::disable);

http.sessionManagement(configure -> configure.sessionCreationPolicy(SessionCreationPolicy.STATELESS))


.authenticationProvider(authenticationProvider())
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class);

http.authorizeHttpRequests(auths -> auths


.requestMatchers("/api/user/**").permitAll()
.requestMatchers("/api/order/**").hasRole("MEMBER")
.requestMatchers("/api/employee/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());

return http.build();
}
R2S Academy - Internal Use 23
Spring Security (14)
Implement
• Configure WebSecurity (cont):
@Bean
public UserDetailsService userDetailsService() {
return username -> userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found" + username));
}

@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());

return authenticationProvider;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
R2S Academy - Internal Use 24
Keeping up those inspiration and the enthusiasm in the learning path.
Let confidence to bring it into your career path for getting gain the success as
your expectation.

Thank you
Contact
- Name: R2S Academy
- Email: [email protected]
Questions and Answers
- Hotline/Zalo: 0919 365 363
- Website: https://r2s.edu.vn
- Fanpage: https://www.facebook.com/r2s.tuyendung

R2S Academy - Internal Use 25

You might also like