I’m working on Android app using Clean Architecture pattern and I have doubts how to implement authorization in a clean way. Is the following solution clean in terms of clean architecture?
I would create use cases like below (executed from presentation layer):
LoginUseCase(for provided login and password fetches api token via remote service and saves in local token source)
LogoutUseCase(clears token from
LocalTokenSource interface would be stored in domain layer and its implementation in data layer – kind of repository)
And in order to perform token refresh at each app launch (it’s not a use case from the user perspective, right?) I would create
SessionManager component in domain layer.
SessionManager would be responsible for refreshing token and saving it in
LocalTokenSource. Each time activity is started, from its presenter I would execute
refreshToken() on injected
SessionManager. What do you think about the solution?
If it’s clean, then how to handle passing token to the remote service to execute other API methods which require token? Lets say I have
PostsRepository which fetches posts data from remote service. Should I pass token from a use case to the repository method like
repo.getPosts(token)? Or inject
LocalTokenSource to the repository, so it could read the token on its own? Wouldn’t the second option violate Clean Architecture rules, because
LocalTokenSource would be used in 2 layers?
The central question you would have to decide is: Do you want to model authorization (and so the usage of the token) as an aspect of your business logic OR do you want to consider it as an “implementation detail”.
If you decide for the first, having dedicated use cases for it, adding the SessionManager to the domain layer and passing the token to the repositories would be a consistent modeling.
If you decide for the later, login/logout/refresh as well as the existence of the token is probably best kept “behind the scenes”, so in the framework or gateway layer.
Both approaches would follow the rules of the Clean Architecture (as long as you do not violate the dependency rule).