无法在从MVC网站调用的Web API服务中进行身份验证

时间:2015-10-27 15:51:22

标签: c# angularjs asp.net-mvc asp.net-web-api

我有一个使用angular作为前端的ASP.NET MVC网站,然后需要与REST Web API服务进行通信以检索数据。我在我的MVC项目中对自定义提供程序有身份验证逻辑,这一切都可以正常使用ADLDS。但是,对REST Web API的调用没有传递身份验证数据,我无法确定如何将使用MVC进行身份验证的用户传递给REST Web API。

以下是对Web API的示例调用。

 public void ApproveModel(int modelVersionId, string comments)
        {
            var request = new RestRequest("api/modelversion", Method.POST) { RequestFormat = DataFormat.Json };
            request.AddBody(new[] { new ModelAction { ModelActionType = ModelActionConstants.ModelActionApproveModel, ActionParameters = new Dictionary<string, string> { { ModelActionConstants.ModelActionParameterModelVersionId, modelVersionId.ToString(CultureInfo.InvariantCulture) }, {ModelActionConstants.ModelActionParameterComments, comments} } } });
            request.UseDefaultCredentials = true; 
            var response = _client.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
                throw new ServerException(response.Content);            
        }

我的Web API控制器方法(缩写)

 [ValidateAccess(Constants.Dummy, Constants.SECURE_ENVIRONMENT)]        
        public HttpResponseMessage Post(ModelAction[] actions)
        {
         ...
}

我的自定义验证访问属性使用了Thinktecture

public class ValidateAccess : ClaimsAuthorizeAttribute
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ValidateAccess));
        private readonly string _resource;
        private readonly string _claimsAction;

        public ValidateAccess(string claimsAction, string resource)
        {
            _claimsAction = claimsAction;
            _resource = resource;
            XmlConfigurator.Configure();
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {            
            if (actionContext == null) throw new ArgumentNullException("actionContext");
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Log.InfoFormat("User {0} is not authenticated - Not authorizing further. Redirecting to error page.",
                    HttpContext.Current.User.Identity.Name);

                return false;
            }

            // specified users or roles when we use our attribute
            return CheckAccess(actionContext);
        }

        protected override bool CheckAccess(HttpActionContext actionContext)
        {            
            if (_claimsAction == String.Empty && _resource == string.Empty)
            {
                //user is in landing page
                return true;
            }
            return ClaimsAuthorization.CheckAccess(_claimsAction, _resource);
        }
    }

我的问题是

  • 我不熟悉Web Api。 IsAuthorized(HttpActionContext actionContext)是覆盖以在API调用上强制执行访问策略的正确方法吗?

  • 为什么我的用户身份为空?

0 个答案:

没有答案