Note that there are some explanatory texts on larger screens.

plurals
  1. POwebapi IPrincipal and authorize
    primarykey
    data
    text
    <p>this is about security MVC4 RC and "Install-Package Microsoft.AspNet.WebApi".</p> <p>I create a custom Identity : System.Security.Principal.IIdentity where i store some valuable string's and int's in the authentication cookie:</p> <pre><code> [Serializable] public class SiteIdentity : IIdentity { public SiteIdentity(string name, string displayName, int userId, int siteId) { this.Name = name; this.DisplayName = displayName; this.UserId = userId; this.SiteId = siteId; } public SiteIdentity(string name, UserInfo userInfo) : this(name, userInfo.DisplayName, userInfo.UserId, userInfo.SiteId) { if (userInfo == null) throw new ArgumentNullException("userInfo"); this.AuthenticationType = userInfo.AutheticationType; this.ClaimsIdentifier = userInfo.ClaimsIdentifier; } public SiteIdentity(FormsAuthenticationTicket ticket) : this(ticket.Name, UserInfo.FromString(ticket.UserData)) { if (ticket == null) throw new ArgumentNullException("ticket"); } </code></pre> <p>... not complete but i think you guess.</p> <p>But first of all the structure of my webapi controller. I have created and extension controller, from where i extend all my webapi controllers:</p> <pre><code> public class _AuthorizedApiController : ApiController { protected readonly Site.Web.Domain.Services.IUserServices _userServices; public _AuthorizedApiController(Site.Web.Domain.Services.IUserServices userServices) { if (userServices == null) throw new ArgumentNullException("userServices"); this._userServices = userServices; } protected int CurrentUserId { get { return this.User.SiteIdentity().UserId; } } private Site.Web.Domain.Models.User currentUser; public Site.Web.Domain.Models.User CurrentUser { get { return this.currentUser ?? (this.currentUser = this._userServices.GetUserFromIdentity(this.User.SiteIdentity())); } } protected int CurrentSiteId { get { return this.User.SiteIdentity().SiteId; } } } </code></pre> <p>so my webapi controller is:</p> <pre><code> public class ServicioController : _AuthorizedApiController { //http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api //http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling static readonly IServicioStatusRepository repositoryServicioStatus = new ServicioStatusRepository(new Site.Web.Data.DatabaseFactory()); public ServicioController(Site.Web.Domain.Services.IUserServices userServices) : base(userServices) { } public IEnumerable&lt;ServicioStatusA&gt; GetServiciosStatus() { IEnumerable&lt;ServicioStatusA&gt; coleccion; var estevalor = CurrentUser.SiteId; } </code></pre> <p>As you can see i use IoC but the issue is that when i try to read CurrentUser.SiteId. I get this error:</p> <p>Unable to cast object of type 'System.Web.Security.FormsIdentity' to type 'Site.Web.Models.SiteIdentity'.</p> <p>in this return function:</p> <pre><code> public static Site.Web.Models.SiteIdentity SiteIdentity(this System.Security.Principal.IPrincipal principal) { return (Site.Web.Models.SiteIdentity)principal.Identity; } </code></pre> <p>I use this "artifact" in global.asax.cs to keep session and information:</p> <pre><code> public override void Init() { this.PostAuthenticateRequest += this.PostAuthenticateRequestHandler; // this.EndRequest += this.EndRequestHandler; base.Init(); } private void PostAuthenticateRequestHandler(object sender, EventArgs e) { if (IsWebApiRequest()) { string esto = "popopopopo"; } HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (IsValidAuthCookie(authCookie)) { // var formsAuthentication = ServiceLocator.Current.GetInstance&lt;IFormsAuthentication&gt;(); var formsAuthentication = new FormsAuthenticationService(); var ticket = formsAuthentication.Decrypt(authCookie.Value); var siteIdentity = new SiteIdentity(ticket); this.Context.User = new GenericPrincipal(siteIdentity, null); // Reset cookie for a sliding expiration. formsAuthentication.SetAuthCookie(this.Context, ticket); } } </code></pre> <p>and what i guess is that when there is a "normal" MVC call every works fine but when there is a webapi call i can recover everything from the cookie but i´ve got:</p> <p>System.Security.Principal.GenericPrincipal + Identity: Site.Web.Model.SiteIdentity</p> <p>instead of :</p> <p>System.Security.Principal.GenericPrincipal + Identity: System.web.security.FormsIdentity</p> <p>Thank you in advance for your support</p> <p>ADEN-UM:</p> <p>googling i try to keep the Identity in the thread also, so inside PostAuthenticateRequestHandler i type:</p> <pre><code> System.Threading.Thread.CurrentPrincipal = this.Context.User; </code></pre> <p>but now i have for all request the following error in any request not only webapi:</p> <pre><code> [SerializationException: Type is not resolved for member 'Site.Web.Models.SiteIdentity,Site.Web, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null'.] Microsoft.VisualStudio.WebHost.Connection.get_RemoteIP() +0 Microsoft.VisualStudio.WebHost.Request.GetRemoteAddress() +65 System.Web.HttpRequest.get_IsLocal() +23 System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request) +86 System.Web.HttpContextWrapper.get_IsCustomErrorEnabled() +45 System.Web.Mvc.HandleErrorAttribute.OnException(ExceptionContext filterContext) +72 System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception) +115 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass25.&lt;BeginInvokeAction&gt;b__22(IAsyncResult asyncResult) +105 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45 System.Web.Mvc.&lt;&gt;c__DisplayClass1d.&lt;BeginExecuteCore&gt;b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.&lt;&gt;c__DisplayClassb.&lt;BeginProcessRequest&gt;b__4(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.&lt;&gt;c__DisplayClasse.&lt;EndProcessRequest&gt;b__d() +50 System.Web.Mvc.SecurityUtil.&lt;GetCallInAppTrustThunk&gt;b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +184 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload