Hi everyone!
I have a base class
AuthenticatorBase that has ability to log in users with different authentication subjects - login & password and token.
Class looks like this:
public abstract class AuthenticatorBase {
public abstract LogInResult LogIn(object authSubject);
public abstract void LogOut(string sessionKey);
}
The sub-class that authenticates with login & password
public class BasicAuthenticator : AuthenticatorBase {
public override LogInResult Authenticate(object authSubject) {
LogInData credentials = authSubject as LogInData;
if (DbContext.Security.Authorize(credentials))
...............
}
}
The sub-class that authenticates with token
public class TokenBasedAuthenticator: AuthenticatorBase {
public override LogInResult Authenticate(object authSubject)
{
string token = authSubject as string;
User user;
if (DbContext.Security.LogInWithToken(token, out user))
...........
}
}
What I don't like in this code is the parameter
authSubject of type
System.Object, I need to cast it in sub-classes. If I use, say
BasicAuthenticator, I might pass invalid type as parameter.
I know I can make generic type
AuthenticatorBase<TAuthSubject> and have two sub-classes
BasicAuthenticator: AuthenticatorBase<LogInData> and
TokenBasedAuthenticator : AuthenticatorBase<string>. But what if I need to have them in list, both generic classes don't have a common interface.
I could create an additional interface like this:
public interface IAuthenticator {
LogInResult LogIn(object authSubject);
}
public abstract class AuthenticatorBase<tauthsubject>: IAuthenticator {
public abstract LogInResult LogIn(TAuthSubject authSubject);
LogInResult IAuthenticator.LogIn(object authSubject)
{
return LogIn((TAuthSubject)authSubject);
}
}
Now I can store instances of
IAuthenticator in the list, but this seems to be very overwhelmed. What's the best way to get rid of the parameter
authSubject as type
System.Object??? I want to call it and pass correct instance of type to authenticators without having to think about correct types that authenticator accepts. Thanks
What I have tried:
Tried to use my code, but I find it overloaded