Question

I have read the documentation and have successfully implemented a custom authentication layer like below:

public class SmartLaneAuthentication : CredentialsAuthProvider
{
    private readonly SmartDBEntities _dbEntities;

    public SmartLaneAuthentication(SmartDBEntities dbEntities)
    {
        _dbEntities = dbEntities;
    }

    public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
    {
        var user = _dbEntities.Users.FirstOrDefault(x => !((bool)x.ActiveDirectoryAccount) && x.UserName == userName);
        if (user == null) return false;

        // Do my encryption, code taken out for simplicity

        return password == user.Password;
    }

    public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
    {
        // user should never be null as it's already been authenticated
        var user = _dbEntities.Users.First(x => x.UserName == session.UserAuthName);
        var customerCount = _dbEntities.Customers.Count();
        session.UserName = user.UserName;
        session.DisplayName = user.DisplayName;
        session.CustomerCount = customerCount; // this isn't accessible?

        authService.SaveSession(session, SessionExpiry);
    }
}

I then register it in AppHost:

Plugins.Add(new AuthFeature(() => new SmartLaneUserSession(), 
    new IAuthProvider[]
    {
        new SmartLaneAuthentication(connection)
    })
{
    HtmlRedirect = null
});

Plugins.Add(new SessionFeature()); 

Notice I'm using a SmartLaneUserSession like below, where I have added a Custom Property called CustomerCount:

public class SmartLaneUserSession : AuthUserSession
{
    public int CustomerCount { get; set; }
}

When I try and access this property to set it in the OnAuthenticated method of my SmartLaneAuthentication class, it isn't accessible. How would I access and set this property when the user is logged in?

Était-ce utile?

La solution

In the OnAuthenticated method you will need to cast the session (of type IAuthSession) into your session object type, such as:

...
var customerCount = _dbEntities.Customers.Count();
var smartLaneUserSession = session as SmartLaneUserSession;
if(smartLaneUserSession != null)
{
    smartLaneUserSession.UserName = user.UserName;
    smartLaneUserSession.DisplayName = user.DisplayName;
    smartLaneUserSession.CustomerCount = customerCount; // Now accessible

    // Save the smartLaneUserSession object
    authService.SaveSession(smartLaneUserSession, SessionExpiry);
}

In your service you can access the session using the SessionAs<T> method. So in your case you can use:

public class MyService : Service
{
    public int Get(TestRequest request)
    {
        var session = SessionAs<SmartLaneUserSession>();
        return session.CustomerCount;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top