首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebApi和MVC控制器的基于角色的自定义授权

WebApi和MVC控制器的基于角色的自定义授权
EN

Stack Overflow用户
提问于 2014-06-04 14:02:20
回答 1查看 448关注 0票数 0

我使用mvc控制器进行登录,使用webapi控制器进行REST操作。我需要根据登录时设置的用户角色对web api控制器进行授权。经过很长一段时间的搜索,我知道我们可以使用表单身份验证。我认为问题是cookie的值也可以从不同的应用程序访问吗?我们如何从mvc设置webapi的值并从Iprinciple访问。有可能吗?如果是,那么你能提供一些示例代码吗?

当前方法:

从MVC设置cookie:

代码语言:javascript
复制
SessionWrapper.CustomPrincipalModel = customPrincipalModel;
            string userData = JsonConvert.SerializeObject(customPrincipalModel);

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
              1, customPrincipalModel.LogonName, DateTime.Now, DateTime.Now.AddHours(8), false, userData);
            string encTicket = FormsAuthentication.Encrypt(authTicket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            Response.Cookies.Add(cookie);

从webapi筛选器属性读取cookie。

代码语言:javascript
复制
var header = filterContext.Request.Headers.GetCookies(FormsAuthentication.FormsCookieName);
            if (header != null && header.Count > 0)
            {
                //// Take out the cookie 
                var authCookie = header.First().Cookies.First(one => one.Name == FormsAuthentication.FormsCookieName);
                //// Create forms-authentication ticket based on the encrypted forms-authentication ticket. 
                var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                if (ticket != null)
                {
                    //// Get the roles associated for the current user
                    var result = JsonConvert.DeserializeObject<CustomPrincipalModel>(ticket.UserData);
                    CustomPrincipal principal = new CustomPrincipal(new GenericIdentity(result.LogonName), result.AccessLevels);
                    principal.CustomPrincipalModel = result;
                    this.CurrentUser = principal;
                }
            }

            if (!string.IsNullOrEmpty(this.Roles))
            {
                if (this.CurrentUser.IsInRole(this.Roles))
                {
                    return true;
                }
            }
EN

回答 1

Stack Overflow用户

发布于 2015-01-30 22:30:54

您可以对web应用程序接口使用基于令牌的身份验证。此处是链接http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24030114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档