2016-09-12 88 views
0

我需要使用cookie身份驗證配置我的asp.net應用程序的幫助。這是我的配置是什麼樣子:使用[授權]屬性時未驗證身份驗證Cookie

public void ConfigureAuth(IAppBuilder app) 
{ 
    app.CreatePerOwinContext(ApplicationDbContext.Create); 
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 

    app.UseCookieAuthentication(new CookieAuthenticationOptions() 
    { 
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
     CookieSecure = CookieSecureOption.SameAsRequest, 
    }); 

    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

    PublicClientId = "self"; 
    OAuthOptions = new OAuthAuthorizationServerOptions 
    { 
     TokenEndpointPath = new PathString("/Token"), 
     Provider = new ApplicationOAuthProvider(PublicClientId), 
     AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
     AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
     AllowInsecureHttp = true 
    }; 

    app.UseOAuthBearerTokens(OAuthOptions); 
} 

我的登錄API的路線是:

[Route("Login")] 
[HttpPost] 
[AllowAnonymous] 
public IHttpActionResult Login(RegisterBindingModel model) 
{ 
    var user = UserManager.Find(model.Username, model.Password); 

    if (user != null) 
    { 
     Authentication.SignOut(); 
     var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); 
     identity.AddClaim(new Claim(ClaimTypes.Role, "IsAdmin")); 
     Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity); 

     return Ok("Success"); 
    } 

    return Ok(); 
} 

調用登錄返回一個名爲.AspNet.ApplicationCookie餅乾,但是當我打電話註銷行動:

[Route("Logout")] 
[HttpPost] 
public IHttpActionResult Logout() 
{    
    Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); 
    return Ok(); 
} 

我收到以下錯誤:Authoriza這項要求已被拒絕

我做錯了什麼?

注:我飾有[授權]控制器屬性

+0

你有2個不同的MVC和WebAPI項目在這種情況下檢查我的答案在這裏 - http://stackoverflow.com/questions/38424518/use-web-api-cookie-for-mvc-cookie/38428420#38428420 。順便說一句,你的問題只有註銷或所有控制器裝飾了[授權]屬性 –

+0

您的評論讓我看看我的Web API配置設置,只是意識到它只被配置爲允許持票人令牌。我刪除了對SuppressDefaultHostAuthentication的調用,現在一切正常。感謝您指點我正確的方向。 – Draco

+0

哦,是的默認模板總是有。很高興你知道了。 –

回答

2

看着我的網絡API配置設置僅用於意識到它僅被配置爲允許承載令牌。我刪除了對SuppressDefaultHostAuthentication的調用,現在一切正常。

0

請檢查您的global.asax.cs() - 那裏我們已經註冊GlobalFilters

​​