ASP.Net Web API授权属性不起作用

时间:2015-01-12 22:51:39

标签: c# asp.net asp.net-web-api

尝试在我的Web API中使用 [授权] 属性。

我希望返回消息为401,但是当我调用我的api时,该函数仍会显示数据(这应该仅在api调用被授权时才有效)。

不确定如何(或在何处)为我设置调试断点以验证[Authorize]属性是否按预期工作。

我的控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using System.Web.Http.Description;
using TestAppVVV.API;
using TestAppVVV.API.Models;

namespace TestAppVVV.API.Controllers
{
    [Authorize]
    [RoutePrefix("api/applicationmodules")]
    public class ApplicationModulesController : ApiController
    {
        private AuthContext db = new AuthContext();

        // GET: api/ApplicationModules
        public IQueryable<ApplicationModule> GetApplicationModules()
        {
            return db.ApplicationModules;
        }

        // GET: api/ApplicationModules/5
        [ResponseType(typeof(ApplicationModule))]
        public IHttpActionResult GetApplicationModule(long id)
        {
            ApplicationModule applicationModule = db.ApplicationModules.Find(id);
            if (applicationModule == null)
            {
                return NotFound();
            }

            return Ok(applicationModule);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool ApplicationModuleExists(long id)
        {
            return db.ApplicationModules.Count(e => e.applicationModuleID == id) > 0;
        }
    }
}

除了执行API调用之外,我还需要在哪里设置断点来检查并验证是否正在执行AUTHORIZE属性?

更新: 我试图在实际的API函数(即:)

之前设置[Authorize]属性
// GET: api/ApplicationModules
        [Authorize]
        public IQueryable<ApplicationModule> GetApplicationModules()
        {
            return db.ApplicationModules;
        }

但仍然得到相同的结果。

更新:我正在使用的授权是 Microsoft.AspNet.Identity.EntityFramework;

AuthorizationProvider:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (Repository _repo = new Repository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "User Name or Password provided is Invalid.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }

Startup.cs

[assembly: OwinStartup(typeof(TestAppVVV.API.Startup))]
namespace TestAppVVV.API
{
    public class Startup
    {
        public void Configuration(IAppBuilder iApp)
        {
            HttpConfiguration htConfig = new HttpConfiguration();

            ConfigureOAuth(iApp);

            WebApiConfig.Register(htConfig);
            iApp.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            iApp.UseWebApi(htConfig);
        }

        public void ConfigureOAuth(IAppBuilder iApp)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token
            iApp.UseOAuthAuthorizationServer(OAuthServerOptions);
            iApp.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }
}

0 个答案:

没有答案