I have ASP.NET MVC app with custom Authentication server. When user wants to log in, app popups window, and when he is done, token returns, and app then logs in user via WebApi,
var cl = from d in (this.User.Identity as ClaimsIdentity).Claims
select new Claim(d.Type, d.Value);
var identity = new ClaimsIdentity(cl, "ApplicationCookie");
AuthenticationManager.SignIn(identity);
var name = cl.FirstOrDefault(x => x.Type.ToLower() == "login").Value;
Thread.CurrentPrincipal = new TaiAuthPrincipal(identity);
System.Web.Security.FormsAuthentication.SetAuthCookie(name, true);
and on every request - WebApi knows who is user, mean User.Identity
is defined;
But in MVC views, it's always null and none of this execute
<div class="headerPane">
@{
if (User.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
if (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
}
</div>
How to authenticate user from web api to mvc? App based on angularjs on front, so all authorization stuff is done on frontend, via webapi requests. So mvc simply doesnt know anything.
For the sake of fullness, this is TaiAuthPrincipal, there is nothing special indeed
public class TaiAuthPrincipal : IPrincipal
{
private IIdentity identity;
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
var _role = (this.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type.ToLower().Contains("GroupName".ToLower()));
return _role == null ? false : true;
}
public TaiAuthPrincipal(IIdentity _identity)
{
this.identity = _identity;
}
public TaiAuthPrincipal(ClaimsIdentity _identity)
{
this.identity = _identity as IIdentity;
}
}
Global.asax
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.AbsolutePath.StartsWith("/api/"))
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
}
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions());
}
}