Skip to content

Instantly share code, notes, and snippets.

@ultimatemonty
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ultimatemonty/12a46ae3595e2729b4ac to your computer and use it in GitHub Desktop.
Save ultimatemonty/12a46ae3595e2729b4ac to your computer and use it in GitHub Desktop.
Custom Authentication
public override void Configure(Container container)
{
// other stuff omitted for brevity
// caching
container.Register<ICacheClient>(new MemoryCacheClient());
// Form based credentials authentication
this.Plugins.Add(new AuthFeature(() => new CustomAuthUserSession(),
new IAuthProvider[] {
// more providers can be added here as required
new CustomCredentialsAuthProvider(),
})
);
container.Register<IUserAuthRepository>(c => new CustomAuthUserRepository());
}
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
private class CredentialsAuthValidator : AbstractValidator<Authenticate>
{
public CredentialsAuthValidator()
{
RuleFor(x => x.UserName).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var authRepo = authService.TryResolve<IAuthRepository>().AsUserAuthRepository(authService.GetResolver());
IUserAuth user;
if (authRepo.TryAuthenticate(userName, password, out user))
{
return true;
}
return false;
}
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
{
new CredentialsAuthValidator().ValidateAndThrow(request);
try
{
base.Authenticate(authService, session, request);
string username = request.UserName;
string password = request.Password;
string referrerUrl = request.Continue;
if (TryAuthenticate(authService, username, password))
{
CustomAuthUserSession customSession = session.ConvertTo<CustomAuthUserSession>();
customSession = _getSession(username);
if (customSession.SubscriptionValid)
{
var response = OnAuthenticated(authService, session, null, null);
if (response != null)
return response;
if (!customSession.SubscriptionValid)
{
throw HttpError.Unauthorized("Your subscription out of date. Please contact your administrator");
}
return new CustomAuthenticateResponse
{
UserId = customSession.UserAuthId,
UserName = customSession.UserName,
SessionId = session.Id,
ReferrerUrl = session.ReferrerUrl,
SubscriptionValid = true
};
}
}
}
catch (Exception ex)
{
throw HttpError.NotFound(ex.Message);
}
// failed to authenticate - throw an error
throw HttpError.Unauthorized(ErrorMessages.InvalidUsernameOrPassword);
}
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
return base.OnAuthenticated(authService, session, tokens, authInfo);
}
private CustomAuthUserSession _getSession(string username)
{
return new CustomAuthUserSession(username);
}
}
public class CustomAuthUserSession : AuthUserSession
{
public CustomAuthUserSession () {}
public CustomAuthUserSession(string username) : base()
{
try
{
Query query = new Query("SelectUserForAuthentication");
query.AddParameter("username", username);
DataRow result = query.ReturnRow();
if (DatabaseUtils.SQLInteger(result["id"]) > 0)
{
// valid result returned
this.UserAuthId = DatabaseUtils.SQLString(result["id"]);
this.UserName = username;
this.FirstName = DatabaseUtils.SQLString(result["firstName"]);
this.LastName = DatabaseUtils.SQLString(result["lastName"]);
this.Id = base.Id;
this.CreatedAt = DateTime.UtcNow;
}
}
catch (Exception ex)
{
throw;
}
}
public Boolean SubscriptionValid { get; set; }
}
public class CustomAuthenticateResponse : AuthenticateResponse
{
public bool SubscriptionValid { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment