search
HomeBackend DevelopmentPython TutorialCREATING AN AUTHENTICATION SERVICE IN PYTHON USING SALT

Coming across an authentication system as a programmer is very common because today almost every web system needs to control and maintain its customers' data and as most of them are sensitive resources, it is necessary to keep them secure. I like to think that security, like many non-functional requirements of an API, can be measured or tested by imagining various scenarios. In an authentication service, for example, we can think: what if someone tries to discover a user's password through brute force, what if another user tries to use another client's access token, what if, accidentally, two users create their credentials with the same password, etc.

By imagining these situations, we can anticipate and create preventive measures. Creating criteria for the password can make it very difficult to discover through brute force, or applying a rate limit to your API can prevent malicious actions, for example. In this article I intend to focus on the problem of the last scenario. Two users registering on the same system with the same password is a serious breach in the system.

It is good practice to keep user passwords encrypted at the bank, which keeps data safer from leaks. The code below shows how a simple credential registration system works in Python.

@dataclass
class CreateCredentialUsecase:
    _credential_repository: CredentialRepositoryInterface
    _password_salt_repository: PasswordSaltRepositoryInterface

    async def handle(self, data: CreateCredentialInputDto) -> CreateCredentialOutputDto:
        try:
            now = datetime.now()

            self.__hash = sha256()
            self.__hash.update(data.password.encode())
            self.__credential = Credential(
                uuid4(), data.email, self.__hash.hexdigest(), now, now
            )

            credential_id = await self._credential_repository.create(self.__credential)

            return CreateCredentialOutputDto(UUID(credential_id))
        except Exception as e:
            raise e

The first 4 lines are the class definition using the @dataclass decorator to omit the constructor method, its properties and the function signature. Inside the try/except block, the current timestamp is first defined, we instantiate the Hash object, update it with the password that is provided, save it in the bank and, finally, return the credential id to the user. Here you might think "okay... if the password is encrypted I don't need to worry, right?". However, this is not the case and I will explain.

What happens is that when passwords are encrypted this is done through a hash, a type of data structure that maps an input to a final value, however, if two inputs are the same, the same password is stored. This is the same as saying that the hash is deterministic. Note the example below that illustrates a simple table in a database that stores the user and hash.

user password
alice@example.com 5e884898da28047151d0e56f8dc6292773603d0d
bob@example.com 6dcd4ce23d88e2ee9568ba546c007c63e8f6f8d6
carol@example.com a3c5b2c98b4325c6c8c6f6e6dbda6cf17b5d7f9a
dave@example.com 1a79a4d60de6718e8e5b326e338ae533
eve@example.com 5e884898da28047151d0e56f8dc6292773603d0d
frank@example.com 7c6a180b36896a8a8c6a2c29e7d7b1d3
grace@example.com 3c59dc048e885024e146d1e4d9d0e4b2

Neste exemplo, as linhas 1 e 5 compartilham o mesmo hash e, portanto, a mesma senha. Para contornarmos esse problema podemos utilizar o salt.

Vamos colocar um pouco de sal nessa senha...

CRIANDO UM SERVIÇO DE AUTENTICAÇÃO EM PYTHON UTILIZANDO SALT

A ideia é que no momento do cadastro do usuário uma string seja gerada de forma aleatória e seja concatenada a senha do usuário antes das credenciais serem salvas no banco. Em seguida esse salt é salvo em uma tabela separada e deve ser utilizada novamente durante o login do usuário. O código alterado ficaria como o exemplo abaixo:

@dataclass
class CreateCredentialUsecase:
    _credential_repository: CredentialRepositoryInterface
    _password_salt_repository: PasswordSaltRepositoryInterface

    async def handle(self, data: CreateCredentialInputDto) -> CreateCredentialOutputDto:
        try:
            now = datetime.now()

            self.__salt = urandom(32)
            self.__hash = sha256()
            self.__hash.update(self.__salt + data.password.encode())
            self.__credential = Credential(
                uuid4(), data.email, self.__hash.hexdigest(), now, now
            )
            self.__salt = PasswordSalt(
                uuid4(), self.__salt.hex(), self.__credential.id, now, now
            )

            credential_id = await self._credential_repository.create(self.__credential)
            await self._password_salt_repository.create(self.__salt)

            return CreateCredentialOutputDto(UUID(credential_id))
        except Exception as e:
            raise e

Agora é possível notar o salt gerado na linha 59. Em seguida ele é utilizado para gerar o hash junto com a senha que o usuário cadastrou, na linha 61. Por fim ele é instanciado através da classe PasswordSalt na linha 65 e armazenado no banco na linha 70. Por último, o código abaixo é o caso de uso de autenticação/login utilizando o salt.

@dataclass
class AuthUsecase:
    _credential_repository: CredentialRepositoryInterface
    _jwt_service: JWTService
    _refresh_token_repository: RefreshTokenRepositoryInterface

    async def handle(self, data: AuthInputDto) -> AuthOutputDto:
        try:

            ACCESS_TOKEN_HOURS_TO_EXPIRATION = int(
                getenv("ACCESS_TOKEN_HOURS_TO_EXPIRATION")
            )
            REFRESH_TOKEN_HOURS_TO_EXPIRATION = int(
                getenv("REFRESH_TOKEN_HOURS_TO_EXPIRATION")
            )

            self.__credential = await self._credential_repository.find_by_email(
                data.email
            )

            if self.__credential is None:
                raise InvalidCredentials()

            self.__hash = sha256()
            self.__hash.update(
                bytes.fromhex(self.__credential.salt) + data.password.encode()
            )

            if self.__hash.hexdigest() != self.__credential.hashed_password:
                raise InvalidCredentials()

            access_token_expiration_time = datetime.now() + timedelta(
                hours=(
                    ACCESS_TOKEN_HOURS_TO_EXPIRATION
                    if ACCESS_TOKEN_HOURS_TO_EXPIRATION is not None
                    else 24
                )
            )
            refresh_token_expiration_time = datetime.now() + timedelta(
                hours=(
                    REFRESH_TOKEN_HOURS_TO_EXPIRATION
                    if REFRESH_TOKEN_HOURS_TO_EXPIRATION is not None
                    else 48
                )
            )

            access_token_payload = {
                "credential_id": self.__credential.id,
                "email": self.__credential.email,
                "exp": access_token_expiration_time,
            }

            access_token = self._jwt_service.encode(access_token_payload)

            refresh_token_payload = {
                "exp": refresh_token_expiration_time,
                "context": {
                    "credential": {
                        "id": self.__credential.id,
                        "email": self.__credential.email,
                    },
                },
            }

            refresh_token = self._jwt_service.encode(refresh_token_payload)
            print(self._jwt_service.decode(refresh_token))

            now = datetime.now()

            await self._refresh_token_repository.create(
                RefreshToken(
                    uuid4(),
                    refresh_token,
                    False,
                    self.__credential.id,
                    refresh_token_expiration_time,
                    now,
                    now,
                    now,
                )
            )

            return AuthOutputDto(
                UUID(self.__credential.id),
                self.__credential.email,
                access_token,
                refresh_token,
            )
        except Exception as e:
            raise e

O tempo de expiração dos tokens é recuperado através de variáveis de ambiente e a credencial com o salt são recuperados através do email. Entre as linhas 103 e 106 a senha fornecida pelo usuário é concatenada ao salt e o hash dessa string resultante é gerado, assim é possível comparar com a senha armazenada no banco. Por fim acontecem os processos de criação dos access_token e refresh_token, o armazenamento do refresh_token e o retorno dos mesmos ao client. Utilizar essa técnica é bem simples e permite fechar uma falha de segurança no seu sistema, além de dificultar alguns outros possíveis ataques. O código exposto no texto faz parte de um projeto maior meu e está no meu github: https://github.com/geovanymds/auth.

Espero que esse texto tenha sido útil para deixar os processos de autenticação no seu sistem mais seguros. Nos vemos no próximo artigo!

The above is the detailed content of CREATING AN AUTHENTICATION SERVICE IN PYTHON USING SALT. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment