TT#12: "Tech talk on Authentication & Authorization"

TT#12: "Tech talk on Authentication & Authorization"

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:

  • Credentials: Common authentication methods include something you know (e.g., passwords), something you have (e.g., smart cards), or something you are (e.g., biometrics).
  • Protocols: Authentication is often facilitated through protocols like OAuth, OpenID, or SAML, depending on the context.

Authorization:

  • Access Control Lists (ACLs): These lists specify what actions or operations are allowed or denied for specific users or system entities.
  • Role-Based Access Control (RBAC): Assigns permissions based on roles, simplifying authorization management.
  • Token-based Authorization: Tokens generated during authentication often carry information about the user's permissions, aiding in authorization decisions.

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:

  1. User Input: The process kicks off when a user provides identification information, such as a username and password, to access a system or application.
  2. Credential Validation: The system checks the provided credentials against a securely stored set in its authentication database. This database houses user information, often hashed or encrypted for added security.
  3. Hashing and Encryption: For enhanced security, passwords are typically stored using cryptographic techniques like hashing or encryption. Hash functions convert passwords into fixed-length strings, making it computationally challenging to reverse the process.
  4. Token Generation (Optional): In modern web applications, tokens may be generated upon successful authentication. These tokens serve as proof of authentication and are often time-limited for added security.
  5. Session Establishment: Upon successful authentication, a session is established between the user and the system. This session, usually associated with a unique identifier, may involve the generation of session cookies.

Authorization:

  1. User Context: With the user authenticated, the system now has a context for the user, including their identity, roles, and possibly additional attributes.
  2. Access Control Decision: The system evaluates access control policies, including Access Control Lists (ACLs), Role-Based Access Control (RBAC), or other rule-based mechanisms. These policies define the actions or resources the user is allowed to access.
  3. Authorization Token (Optional): If tokens were generated during authentication, they may contain information about the user's authorization level. This information is extracted and used to make fine-grained authorization decisions.
  4. Enforcement of Policies: The system enforces access control policies by allowing or denying access to specific resources or functionalities based on the user's identity and permissions.
  5. Logging and Auditing (Optional): Systems may log authorization decisions for auditing purposes. This log can be essential for tracking who accessed what resources and when. ????


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:

  1. Password-Based Authentication: The ubiquitous method where users reveal a secret password to prove their identity.
  2. Two-Factor Authentication (2FA): Adding an extra layer of security by combining something known (password) with something possessed (token or smartphone).
  3. Biometric Authentication: Harnessing unique human features like fingerprints, voice, or retinal scans for identity verification.
  4. Certificate-Based Authentication: Using digital certificates, issued by trusted authorities, to verify user identity (e.g., SSL certificates).
  5. Single Sign-On (SSO): Streamlining access by allowing users to use one set of credentials across multiple applications.
  6. OAuth 2.0: Initially an authorization framework, OAuth 2.0 doubles as an authentication tool, enabling controlled access to HTTP services.
  7. OpenID Connect: A layer atop OAuth 2.0, providing a straightforward identity verification mechanism.
  8. Token-Based Authentication: This method involves providing the user with a token during the sign-in process. This token, which is typically added to the header of HTTP requests, serves as a passkey for accessing resources. The server checks the validity of the token and, if valid, provides access to the requested resources. Tokens can carry information about the user’s identity and permissions, reducing the need for repeated database lookups.

Authorization

Authorization, the guardian of resources, follows once a user's identity is confirmed:

  1. Role-Based Access Control (RBAC): Dictates access based on a user's role within an organization, ensuring access aligns with job responsibilities.
  2. Discretionary Access Control (DAC): Empowers resource owners to decide access permissions based on user identity or role.
  3. Mandatory Access Control (MAC): The system, not users, governs access, often using labels or classification levels.
  4. Attribute-Based Access Control (ABAC): Leverages attributes like department or job title to determine user access rights.
  5. OAuth 2.0: Serving dual purposes, OAuth 2.0 authorizes third-party applications while ensuring limited access to user accounts.
  6. Access Control List (ACL): An OS's guide, detailing user access rights for system objects, such as files or directories.

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! ??

要查看或添加评论,请登录

Satyam Barsainya的更多文章

社区洞察

其他会员也浏览了