我试图使服务只能在客户端经过身份验证并且我放置了 Authenticate 属性的情况下才能访问,但它不起作用,因为当我可以在未经身份验证的情况下访问服务时。我将 Authenticate 属性放在 Request DTO 之前、服务顶部和 Action 之前。这是我要保护的服务的一些代码
[Authenticate]
public class HelloService : Service
{
public const string HelloServiceCounterKey = "HelloServiceCounter";
public object Any(HelloRequest request)
{
var userSession = SessionAs<AppHost.CustomUserSession>();
Session.Set(HelloServiceCounterKey, Session.Get<int>(HelloServiceCounterKey) + 1);
var roles = string.Join(", ", userSession.Roles.ToArray());
return new HelloResponse { Result = "Hello, " + request.Name + ", your role(s): " + roles };
}
}
我的 AppHost 配置中有这个(Funq.Container 容器)
Plugins.Add(new AuthFeature(
() => new CustomUserSession(),
new[] { new CustomCredentialsAuthProvider() }
));
public class CustomUserSession : AuthUserSession
{
public string CompanyName { get; set; }
}
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (!Membership.ValidateUser(userName, password)) return false;
var session = (CustomUserSession)authService.GetSession(false);
session.CompanyName = "Company from DB";
session.UserAuthId = userName;
session.IsAuthenticated = true;
// add roles
session.Roles = new List<string>();
if (session.UserAuthId == "admin") session.Roles.Add(RoleNames.Admin);
session.Roles.Add("User");
return true;
}
}
当访问该行中的服务时
var roles = string.Join(", ", userSession.Roles.ToArray());
显然返回 NULL 因为尚未经过身份验证。
在这种情况下应该做什么 Authenticate 属性?