0

我需要帮助使用 cookie 身份验证配置我的 asp.net 应用程序。这是我的配置的样子:

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的 cookie ,但是当我调用注销操作时:

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

我收到以下错误:此请求的授权已被拒绝

我究竟做错了什么?

注意:我用[Authorize]属性装饰了控制器

4

2 回答 2

2

查看我的 Web API 配置设置,却发现它仅配置为允许不记名令牌。我删除了对 SuppressDefaultHostAuthentication 的调用,现在一切正常。

于 2016-10-11T07:53:30.243 回答
0

请检查您的 global.asax.cs() - 我们必须在那里注册 GlobalFilters

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
于 2016-09-13T18:24:08.570 回答