我已经阅读了文档,并成功实现了一个自定义身份验证层,如下所示:
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
下面使用“ like”,在其中添加了一个名为的自定义属性CustomerCount
:
public class SmartLaneUserSession : AuthUserSession
{
public int CustomerCount { get; set; }
}
当我尝试访问该属性以在类的OnAuthenticated
方法中对其进行设置时,将SmartLaneAuthentication
无法访问它。用户登录后如何访问和设置此属性?
在OnAuthenticated
方法中,您需要将session
(类型为IAuthSession
)转换为会话对象类型,例如:
...
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句