TT#12: "Tech talk on Authentication & Authorization"
Satyam Barsainya
Staff Engineer @ Altimetrik | Ex-Publicis Sapient | Ex-Wipro | Java | Spring Boot | Flutter | HTML | CSS | Angular Specialist | API & Microservices Expert | Technical Blogger
Authentication and Authorization: Safeguarding Access to Resources ???
Authentication and authorization are pivotal in securing access to resources, forming the bedrock of robust security protocols.
?? Authentication:
Authentication is the process of verifying the identity of a user, system, or entity. It ensures that the claimed identity is genuine and accurate. In other words, it answers the question, "Who are you?" Authentication involves presenting credentials, such as a username and password, a fingerprint, or a security token, and validating them against a trusted source.
?? Authorization:
Authorization, on the other hand, is the process of determining what actions or operations an authenticated user or system is allowed to perform. Once a user's identity is established through authentication, authorization defines the level of access they have to specific resources or functionalities. It answers the question, "What are you allowed to do?"
Analogy:
Think of authentication as the process of checking your ID at the entrance of a secure building. The security guard ensures that the ID is valid and matches your face, confirming your identity. Once inside, authorization determines which areas you can access – whether you can enter certain rooms or use particular facilities. The combination of authentication and authorization ensures a secure and controlled environment.
Technical Details:
Authentication:
Authorization:
In a web application, for example, authentication occurs when a user logs in with a username and password. Once authenticated, authorization comes into play to determine whether the user can access certain pages, perform specific actions, or view particular data based on their role or permissions. ???
Internal Workings of Authentication and Authorization: Unveiling the Mechanisms ????
Authentication:
Authorization:
Unlocking the World of Authentication and Authorization! ????
Here's a overview of common types of Authentication and Authorization:
Authentication
Authentication, the gatekeeper of digital realms, encompasses various methods to validate user identity:
Authorization
Authorization, the guardian of resources, follows once a user's identity is confirmed:
Dive into the realm of Authentication and Authorization – safeguarding the digital frontier! ???? #SecurityMatters #CyberGuardians
Below is the code snippet with detailed explanation. ??
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtil jwtUtils;
@Autowired
private MyUserDetailsService myUserDetailsService;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.isValidToken(jwt)) {
String username = jwtUtils.getUsernameFromToken(jwt);
UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7);
}
return null;
}
}
Explanation:
JWT Extraction and Validation:
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.isValidToken(jwt)) {
...
}
This part of the code extracts the JWT (JSON Web Token) from the request and checks if it’s valid.
User Authentication:
String username = jwtUtils.getUsernameFromToken(jwt);
UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
If the JWT is valid, the code extracts the username from the token, loads the user details, and creates an UsernamePasswordAuthenticationToken object. This object represents the authenticated user.
Setting Security Context:
SecurityContextHolder.getContext().setAuthentication(authentication);
The authenticated user is then set in the SecurityContextHolder, which is a holder class that stores details of the security context of the current thread of execution.
领英推荐
Continuing the Filter Chain:
filterChain.doFilter(request, response);
Finally, the filter chain continues with the request and response. This means that the next filter in line will be invoked.
This code is part of a filter that intercepts incoming requests to authenticate the user based on the provided JWT. If the JWT is valid, the user is authenticated and the request is allowed to proceed. If not, an error is logged and the request may be rejected depending on the rest of your security configuration. This is a common pattern in stateless, token-based authentication systems. It ensures that the user is authenticated at the start of each request.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
private static final String[] AuthList = {
"/authenticate",
};
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth ->
auth.requestMatchers(AuthList).permitAll()
.anyRequest().authenticated()
);
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
}
Explanation:
Beans:
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
This method defines a bean for AuthTokenFilter, which is presumably a custom filter for handling JWT (JSON Web Token) authentication.
Authentication Manager:
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
This method exposes the AuthenticationManager bean, which is responsible for authenticating users in Spring Security.
Security Filter Chain:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
...
return http.build();
}
This method sets up the security filter chain with HttpSecurity. It configures various security settings like CSRF protection, session management, and request authorization.
Authentication Provider:
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
This method sets up the DaoAuthenticationProvider bean, which is used by Spring Security to handle authentication with a data access object (DAO). It uses the UserDetailsService to load user-specific data and the BCryptPasswordEncoder to encode passwords.
URL Authorization:
http.authorizeHttpRequests(auth ->
auth.requestMatchers(AuthList).permitAll()
.anyRequest().authenticated()
);
This part of the filterChain method configures URL-based authorization. It allows all requests to the “/authenticate” endpoint and requires authentication for all other requests.
JWT Authentication Filter:
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
This line adds the AuthTokenFilter before the UsernamePasswordAuthenticationFilter in the filter chain.
JWT in Technical Terms: A Quick Dive
?What is JWT?
JWT (JSON Web Token) serves as a sleek, URL-safe method for exchanging claims between two parties. It's a go-to choice for secure authentication and seamless information sharing.
How is it Crafted?
Header: Illuminates how the JWT is encoded (e.g., leveraging HMAC SHA256).
Payload: Transports vital claims, like user ID and role.
Signature: Stamps its integrity and authenticity seal.
How is it Split?
Header.Payload.Signature
Each section encoded and gracefully separated by dots.
Example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Simplicity, security, and a touch of sophistication! ?? #JWT #Authentication
?? Demonstrating Token-Based Authentication with a Hello World Project!
For utmost clarity, behold a Hello World Project designed to exemplify Token-Based Authentication. Brace yourself for the magic: upon entering the correct credentials, users unlock a special JWT (JSON Web Token) – a golden ticket.
?? GitLab Repository: Explore the Code
Let's dive into the fascinating world of secure authentication using tokens! ???
?? Join the Conversation: Share this post with your friends and colleagues who are passionate about web development and tech innovation. Let's learn and grow together. Your network will thank you! ??