我有自定義身份驗證服務器的ASP.NET MVC應用程序。當用戶試圖登錄時,應用程序的彈出窗口,當他完成後,令牌的回報,然後應用在通過的WebAPI用戶登錄,WebApi身份驗證不適用於MVC
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);
,並在每個請求 - 的WebAPI知道誰是用戶,平均User.Identity
是定義; 但在MVC的觀點,它總是空,沒有這個執行
<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>
如何驗證來自網頁API用戶MVC? 基於前面的angularjs的應用程序,所以所有授權內容都通過webapi請求在前端完成。所以mvc根本不知道任何事情。
對於豐滿的緣故,這是TaiAuthPrincipal,沒有什麼特別的確實
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());
}
}
是網絡API是MVC中的同一個項目? – 2015-02-09 05:56:51
是的,他們在1申請 – 2015-02-09 05:59:23
檢查我的答案 – 2015-02-09 06:05:51