servicestack,forms-authentication,C#,Asp.net Mvc,Authentication,servicestack,Forms Authentication" /> servicestack,forms-authentication,C#,Asp.net Mvc,Authentication,servicestack,Forms Authentication" />

C# 这是填充用户';将使用ServiceStack的角色添加到自定义IPrincipal,以便在表单身份验证中进行自动连线授权

C# 这是填充用户';将使用ServiceStack的角色添加到自定义IPrincipal,以便在表单身份验证中进行自动连线授权,c#,asp.net-mvc,authentication,servicestack,forms-authentication,C#,Asp.net Mvc,Authentication,servicestack,Forms Authentication,我正在使用Servicestack作为asp.net mvc应用程序的中间层逻辑/web服务部分。在前端,我使用FormsAuthentication+“auth/credentials”对asp.net和servicestack启用身份验证/授权 在我的一些mvc控制器中,我使用内置的用户(IPrincipal)进行角色/权限检查 [Authorize] public ActionResult Index() { if (!User.IsInRole("admin"))

我正在使用Servicestack作为asp.net mvc应用程序的中间层逻辑/web服务部分。在前端,我使用FormsAuthentication+“auth/credentials”对asp.net和servicestack启用身份验证/授权

在我的一些mvc控制器中,我使用内置的
用户(IPrincipal)
进行角色/权限检查

[Authorize]
public ActionResult Index()
    {
        if (!User.IsInRole("admin"))
            ViewBag.ErrorMessage = "Access Denied";

        return View();
    }
我了解到默认
用户
中的角色在表单身份验证期间不会填充,因此我根据IPrincipal创建了自定义类,并在调用
PostAuthenticateRequest

这是从servicestack获取/设置角色/权限到
HttpContext.Current.User
的正确方法吗

public class CustomPrincipal : IPrincipal
    {
        //private readonly IEnumerable<string> _roles;

        public IIdentity Identity { get; private set; }

        public bool IsInRole(string role)
        {
            // retrieve roles from servicestack cache  
            var key = ServiceStack.ServiceInterface.SessionFeature.GetSessionKey() ?? "";
            var sess = fubar.web.App_Start.AppHost.Resolve<ServiceStack.CacheAccess.ICacheClient>().Get<ServiceStack.ServiceInterface.Auth.AuthUserSession>(key);

            if (sess != null)
                return sess.Roles.Contains(role);
            return false;                
        }

        public CustomPrincipal(string name)
        {
            Identity = new GenericIdentity(name);
            //_roles = roles;
        }

        public long Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }
公共类客户主体:IPrincipal
{
//私有只读IEnumerable\u角色;
公共身份标识{get;private set;}
公共布尔IsInRole(字符串角色)
{
//从servicestack缓存检索角色
var key=ServiceStack.ServiceInterface.SessionFeature.GetSessionKey();
var sess=fubar.web.App_Start.AppHost.Resolve().Get(键);
如果(sess!=null)
返回sess.Roles.Contains(角色);
返回false;
}
公共CustomPrincipal(字符串名称)
{
标识=新的GenericEntity(名称);
//_角色=角色;
}
公共长Id{get;set;}
公共字符串名{get;set;}
公共字符串MiddleName{get;set;}
公共字符串LastName{get;set;}
}
顺便说一句,这是我的登录方法,请检查这是否也是对asp.net进行双重身份验证的正确方法身份验证和服务堆栈:)

试试看
{
var authService=AppHostBase.Resolve();
authService.RequestContext=System.Web.HttpContext.Current.ToRequestContext();
var response=authService.Authenticate(新身份验证
{
用户名=model.UserName,
Password=model.Password,
RememberMe=model.RememberMe
});
var版本=1;
var now=DateTime.now;
var timeout=FormsAuthentication.timeout;
var expire=now.Add(超时);
var user=新用户
{
FirstName=“first”,
MiddleName=“middle”,
LastName=“last”
};
var serializer=新的JavaScriptSerializer();
var userData=serializer.Serialize(用户);
var票证=新表单身份验证票证(
版本
model.UserName,
现在,
到期,
记住,
用户数据);
Response.Cookies.Add(新的HttpCookie)(
FormsAuthentication.FormsScookeName,FormsAuthentication.Encrypt(票证))
{
Secure=FormsAuthentication.RequireSSL
});
FormsAuthentication.GetRedirectUrl(model.UserName,model.RememberMe);
//添加ASP.NET身份验证cookie
//FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
return Url.IsLocalUrl(returnUrl)?重定向(returnUrl):重定向(~/);
}
捕获(HttpError-ex)
{
ModelState.addmodeleror(“,”发生错误。\n“+ex.Message);
}

非常感谢

你到底想知道什么?你说的“正确的方式”是什么意思?它对你有效,对吗?是的,它有效。但我在想,是否有更多的“首选”方式可以做到这一点。我可以重写代码,以便在global.asax中的每个begin请求中设置用户的凭据。或者我可以设置(通过配置)asp.net中内置的“角色”服务提供程序。
try
            {
                var authService = AppHostBase.Resolve<AuthService>();
                authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
                var response = authService.Authenticate(new Auth
                {
                    UserName = model.UserName,
                    Password = model.Password,
                    RememberMe = model.RememberMe
                });

                var version = 1;
                var now = DateTime.Now;

                var timeout = FormsAuthentication.Timeout;
                var expire = now.Add(timeout);

                var user = new User
                {
                    FirstName = "first",
                    MiddleName = "middle",
                    LastName = "last"
                };
                var serializer = new JavaScriptSerializer();
                var userData = serializer.Serialize(user);

                var ticket = new FormsAuthenticationTicket(
                     version,
                     model.UserName,
                     now,
                     expire,
                     model.RememberMe,
                     userData);

                Response.Cookies.Add(new HttpCookie(
                    FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
                    {
                        Secure = FormsAuthentication.RequireSSL
                    });

                FormsAuthentication.GetRedirectUrl(model.UserName, model.RememberMe);

                // add ASP.NET auth cookie
                //FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                return Url.IsLocalUrl(returnUrl) ? Redirect(returnUrl) : Redirect("~/");
            }
            catch (HttpError ex)
            {
                ModelState.AddModelError("", "Error occured.\n" + ex.Message);
            }