使用[授权]属性

时间:2016-09-12 10:38:23

标签: c# asp.net asp.net-mvc owin owin-middleware

我需要帮助使用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();
}

调用login会返回名为 .AspNet.ApplicationCookie 的cookie,但是当我调用注销操作时:

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

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

我做错了什么?

注意:我使用 [授权] 属性

修饰了控制器

2 个答案:

答案 0 :(得分:2)

查看我的Web API配置设置只是为了意识到它只配置为允许承载令牌。我删除了对SuppressDefaultHostAuthentication的调用,现在一切正常。

答案 1 :(得分:0)

请检查你的global.asax.cs() - 我们必须注册GlobalFilters

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }