我已经查看了ServiceStack的身份验证/授权代码的几个示例,但我似乎无法解决此问题。
我创建了一个自定义AuthFeature
,它派生自BasicAuthProvider
并在AppHost的插件中注册。在我的自定义提供程序中,我覆盖了TryAuthenticate
和OnAuthenticated
,在我的服务中,我使用[Authenticate]
和[RequiresAnyRole("Test")]
的属性修饰了该类。在我的用例中,我在我的Auth标头中输入用户名和密码,命中我的服务,调用TryAuthenticate
(并通过身份验证),然后点击OnAuthenticated
方法,我用一个角色填充会话变量(在这种情况下"测试")。结果是403 Invalid Role
。如果我删除了身份验证的RequiresAnyRole
属性,我甚至可以查看当前的会话变量并查看我创建的角色。此外,我尝试了RequiredRole
和RequiredPermission
(通过向会话添加权限),结果相同。
有人可以告诉我,我是否正确添加了具有测试角色的会话,或者我是否正确实施了自定义身份验证提供程序?
我的身份验证提供商代码:
public class AdAuthProvider : BasicAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var authenticated = false;
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), userName);
var adRealm = System.Configuration.ConfigurationManager.AppSettings["ADRealm"];
if (userPrincipal != null)
{
using (var pc = new PrincipalContext(ContextType.Domain, adRealm))
{
authenticated = pc.ValidateCredentials(userName, password);
}
}
return authenticated;
}
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
session.Roles = new List<string>();
session.Roles.Add("Test");
authService.SaveSession(session, new System.TimeSpan(0, 30, 0));
return null;
}
我的服务代码:
[Authenticate]
[RequiresAnyRole("Test")]
public class TestService: Service
{
...
答案 0 :(得分:2)
您需要使用AssignRole
到assignrole
,而不是使用不会持久的会话对象。
查看GitHub上的authRepo
服务代码,了解如何解决var authRepo = HostContext.AppHost.GetAuthRepository(base.Request);
using (authRepo as IDisposable)
{
var userAuth = authRepo.GetUserAuthByUserName(request.UserName);
if (userAuth == null)
throw HttpError.NotFound(request.UserName);
authRepo.AssignRoles(userAuth, request.Roles, request.Permissions);
并分配角色。
SELECT *
FROM
(
SELECT *, ntile(2) over(order by ID) as tile_nr
FROM
(
SELECT bt.*
FROM dbTable b1
INNER JOIN
(
SELECT ID, max(revision) as revision
FROM dbTable
GROUP BY ID as b2
ON b1.ID = b2.revision or b2.revision is null
)
)
) x
WHERE x.tle_nr = 1
https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack/Auth/AssignRolesService.cs