abac

You know that I really unsettles amusing? Even people who have worked in IT for a long time confuse authentication and authorization. On a couple of projects, I came across the fact that some guys who have been working in the industry for years do not see the difference between these two concepts. And it's not easy “I'm freaking out” puzzling – this can be dangerous for the security of systems, since due to a false definition of thoughts they produce completely ambiguous conclusions.

Authentication (AuthN) is a way to confirm that you are who you say you are. This is a passport to the digital world: passwords, various biometrics and other exotic methods are all examples of authentication. It's like saying, “Hi, it's me!”

Authorization (AuthZ) is a different beast. This is about what you can do after you have verified your identity. Imagine that you have entered an online store. Now the question is: can you just view products, add them to your cart, or do you have access to the admin panel to change the assortment? This is authorization – the rules that determine what actions are available to you.

Why is it important to understand the difference? Because when these concepts are confused, big problems arise. For example, if you confuse who can log in to a system (authentication) with what that user can do (authorization), you open the door to a lot of vulnerabilities. So let's be clear once and for all: authentication and authorization are different things, and understanding the difference is important to ensuring the security of your software. They also discuss this issue very well in the article. Authn vs. authz: ​​How are they different? By Cloudflare!

Authentication (AuthN)

Before users can interact with your software, you need to verify that they are who they say they are. This is authentication (Authentication, AuthN). Examples with a password are one of the basic ones, let’s say one of the methods of the first factor.

A simple example of authentication using spring security, which is unlikely to be in Production now! But as an example for visual understanding, this is the case; later in the article I will use simple snippets and leave links to richer options =)

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("ADMIN");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

A fairly good approach is described in this option and even more informative in this turnip.

As you know, modern security systems are increasingly moving to the use of two-factor authentication (2FA) to increase the level of protection. Single-factor authentication, such as using only a password, is no longer considered strong enough due to the many vulnerabilities associated with passwords (such as theft or brute force).

2FA adds an additional layer of security by requiring a second way to verify a user's identity. This is usually a second factor from a different category, for example:

  • Something you know: Password or PIN.

  • Something you have: Smartphone or token.

  • Something that you are: Biometrics such as fingerprints or facial recognition.

Sending SMS

public class TwoFactorAuthenticationService {

    // Метод для отправки SMS
    public void sendSmsCode(String phoneNumber) {
        String code = generateCode();
        // Логика для отправки SMS
        SmsSender.send(phoneNumber, "Ваш код подтверждения: " + code);
        // Сохранение кода в базе данных или кэше
        saveCode(phoneNumber, code);
    }

    // Генерация случайного кода
    private String generateCode() {
        // Логика генерации кода
        return String.valueOf(new Random().nextInt(999999));
    }

    // Сохранение кода
    private void saveCode(String phoneNumber, String code) {
        // Логика сохранения кода (например, в базе данных или кэше)
        CodeRepository.save(phoneNumber, code);
    }
}

Checking the same SMS

@RestController
@RequiredArgsConstructor
public class TwoFactorAuthenticationController {

    private TwoFactorAuthenticationService twoFactorAuthService;

    // Метод для проверки кода
    @PostMapping("/verifyCode")
    public ResponseEntity<String> verifyCode(@RequestParam String phoneNumber, @RequestParam String code) {
        boolean isCodeValid = twoFactorAuthService.verifyCode(phoneNumber, code);
        if (isCodeValid) {
            return ResponseEntity.ok("Код подтвержден успешно");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Неверный код");
        }
    }
}

@Service
public class TwoFactorAuthenticationService {

    // Метод для проверки кода
    public boolean verifyCode(String phoneNumber, String code) {
        String savedCode = getCode(phoneNumber);
        return code.equals(savedCode);
    }

    // Получение кода из базы данных или кэша
    private String getCode(String phoneNumber) {
        // Логика получения кода
        return CodeRepository.findByPhoneNumber(phoneNumber);
    }
}

Yes, yes, it's still pseudocode, this moment is here understands more clearly.

It’s clear that 2FA is not the limit, it’s not for nothing that there is the term MFA, and here everything depends on the specific business needs for your software.

Authorization (AuthZ)

Once the user has been authenticated, the next important task is authorization (Authorization, AuthZ). Authorization determines what a user can do on the system, what resources he has access to, and what actions he can perform. Imagine that you have entered an online store. Now the question is: can you just view products, add them to your cart, or do you have access to the admin panel to change the assortment? This is authorization – the rules that determine what actions are available to you.

Role-Based Access Control (RBAC)

RBAC, or role-based access control, grants access to resources based on the roles (user, moderator, administrator, etc.) assigned to the user. This is one of the most common authentication methods.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers("/", "/home").permitAll()
                .requestMatchers("/user/**").hasRole("USER")
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

Attribute-Based Access Control (ABAC)

ABAC, or attribute-based access control, provides access based on attributes of the user, resources, and environment. This method allows for more flexible access control.

// Пример реализации ABAC может включать сложные правила на основе атрибутов, 
// таких как должность пользователя, время дня или местоположение.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers("/", "/home").permitAll()
                .requestMatchers("/user/**").access("hasRole('USER') and hasIpAddress('192.168.1.0/24')")
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}
// Здесь мы указываем, что доступ к URL, начинающимся с "/user/**", 
// разрешен только пользователям с ролью "USER" и IP-адресом из подсети 
// "192.168.1.0/24". Это пример использования атрибутов для контроля доступа.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .requestMatchers("/", "/home").permitAll()
            .requestMatchers("/user/**").access("hasRole('USER') and hasIpAddress('192.168.1.0/24')")
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll();
}

Thus, modern security systems can use different authorization approaches to provide flexibility and protection. Also a more clear example RBAC/ABAC can be found in this material.

That's the bottom line, Karl!

Authentication and authorization are two different processes that play key roles in keeping your systems secure. Although they are often mentioned together, their goals and methods are radically different.

Not understanding the difference between authentication and authorization can lead to serious security vulnerabilities. For example, strong authentication without appropriate authorization could allow attackers to access sensitive data or functions that they should not have access to. Likewise, even with proper authorization, insufficient authentication can leave the system open to attack. Understanding and properly implementing authentication and authorization helps protect your systems and data from unauthorized access, minimize the risk of information leaks, and improve overall security. These processes are necessary to create reliable and secure applications where each component plays its important role.

Thus, the difference between authentication and authorization is not just a theoretical issue, but an important aspect that affects the security and efficiency of your decisions. Understanding and using these processes correctly helps create more secure systems that meet today's security requirements.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *