Home  >  Article  >  Backend Development  >  CREATING AN AUTHENTICATION SERVICE IN PYTHON USING SALT

CREATING AN AUTHENTICATION SERVICE IN PYTHON USING SALT

WBOY
WBOYOriginal
2024-08-27 06:03:021023browse

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