自定义ServiceStack认证

3

我已经阅读了文档,并成功地实现了自定义身份验证层,如下所示:

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);
    }
}

我接下来在AppHost中进行注册:

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

Plugins.Add(new SessionFeature()); 

请注意,我正在使用以下类似的SmartLaneUserSession,在其中我添加了一个名为CustomerCount的自定义属性:
public class SmartLaneUserSession : AuthUserSession
{
    public int CustomerCount { get; set; }
}

当我尝试在我的 SmartLaneAuthentication 类的 OnAuthenticated 方法中访问并设置这个属性时,它是不可访问的。用户登录后我该如何访问和设置这个属性?


对我来说是个好主意。谢谢兄弟。 - Ersin Tarhan
1个回答

4
OnAuthenticated方法中,您需要将类型为IAuthSessionsession转换为您的会话对象类型,例如:
...
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);
}

在您的服务中,您可以使用SessionAs<T> 方法访问会话。因此,在您的情况下,您可以使用:

public class MyService : Service
{
    public int Get(TestRequest request)
    {
        var session = SessionAs<SmartLaneUserSession>();
        return session.CustomerCount;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接