Okay, so, I'm working on an AuthService for my microservices system.

I'm putting plenty of logic around single instance of User inside of it itself, just so I can avoid repeating code, breaking SRP or anemic domain models.

.. but now I've stumbled upon a certain problem, to be precise:

I have this method inside User entity:

    public Token SignIn(string username, string password)
        if (string.IsNullOrEmpty(username))
            throw new ArgumentNullException("Username cannot be null or empty");

        if (string.IsNullOrEmpty(password))
            throw new ArgumentNullException("Password cannot be null or empty");

        if (Password != password)
            throw new Exception("Password mismatch");

        return Token.Create(this, TokenType.Session, "???");

The problem with this is, token value is supposed to be generated via ITokenValueProvider.

I only see 4 solutions to this problem - all but one of them would break SRP, create a leaky abstraction or break DDD.

a) Add string tokenValue to SignIn and then generate value on the service and push it deeper.

e.g.: public Token SignIn(string username, string password, string tokenValue)

b) Add ITokenValueProvider tokenizer to SignIn and then generate it inside User.SignIn

c) Add ITokenValueProvider tokenizer to public static Token.Create() and then generate it there.

d) Replace SignIn with CanSignIn and then generate token on the service - this solution is the one that would cause no antipatterns, other than being generally ugly and disallows me to store logic around signing-in inside the entity.

Any ideas :) ?

  • There might be a clean solution that uses events. In this method a UserLoggedIn event could be emitted and the token service in the application layer responds to that. But getting that token to the user would be the next challenge.
    – Rik D
    Dec 11, 2021 at 16:02
  • @RikD That sounds like solution a), but instead of passing tokenValue, I pass the Token instance
    – JTinkers
    Dec 11, 2021 at 16:14
  • 1
    I doubt Token is part of your domain, rather, an implementation detail within your application/infrastructure layer. Keep it there. We could imagine all sorts of different ways of managing auth from an application-level PoV right? d is the best solution listed above, but keep the name SignIn and don't return a bool (just throw). To be completely honest though, I don't think any of the above should be in your domain. User doesn't sound like a DDD entity to me. What do Users do? Dec 14, 2021 at 15:03
  • @king-side-slide I've decided that the service isn't complex enough for full DDD. I've used Hexagonal Arch with good practices from DDD (like bounding contexts, non-anemic entities etc.). The issue is solved.
    – JTinkers
    Dec 16, 2021 at 8:07


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.