【问题标题】:MVC-6 vs MVC-5 BearerAuthentication in Web APIWeb API 中的 MVC-6 与 MVC-5 BearerAuthentication
【发布时间】:2015-09-15 08:40:17
【问题描述】:

我有一个使用 UseJwtBearerAuthentication 到我的身份服务器的 Web API 项目。 启动时的配置方法如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
        options.Authority = "http://localhost:54540/";
        options.Audience = "http://localhost:54540/";
    });

    // Configure the HTTP request pipeline.
    app.UseStaticFiles();

    // Add MVC to the request pipeline.
    app.UseMvc();
}

这是可行的,我想在 MVC5 项目中做同样的事情。我试图做这样的事情:

网页接口:

public class SecuredController : ApiController
    {
            [HttpGet]
            [Authorize]
            public IEnumerable<Tuple<string, string>> Get()
            {
                var claimsList = new List<Tuple<string, string>>();
                var identity = (ClaimsIdentity)User.Identity;
                foreach (var claim in identity.Claims)
                {
                    claimsList.Add(new Tuple<string, string>(claim.Type, claim.Value));
                }
                claimsList.Add(new Tuple<string, string>("aaa", "bbb"));

                return claimsList;
            }
}

如果设置属性 [授权],我无法调用 web api(如果我删除它,它就可以工作)

我创建了 Startup。这段代码永远不会被调用,我不知道要改变什么才能让它工作。

[assembly: OwinStartup(typeof(ProAuth.Mvc5WebApi.Startup))]
namespace ProAuth.Mvc5WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            Uri uri= new Uri("http://localhost:54540/");
            PathString path= PathString.FromUriComponent(uri);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = path,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

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

            context.Validated(identity);

        }
    }

}

目标是将声明从 Web api 返回到客户端应用程序。使用承载认证。
感谢您的帮助。

【问题讨论】:

  • 在哪里可以找到 app.UseJwtBearerAuthentication(...) ?您的 project.json 和使用引用(在 Startup.cs 上)是什么样的?
  • "Microsoft.AspNet.Authentication.JwtBearer":"1.0.0-*"
  • 在未调用您的启动代码时,您可能需要一组符合 MVC5 的 nuget 依赖项。我只是使用 Global.asax.cs Application_Start 方法而不是 OwinStartup
  • 你安装了web主机包吗? Microsoft.Owin.Host.SystemWeb 是必需的 - 例如stackoverflow.com/questions/20203982/owinstartup-not-firing
  • 看起来问题已经完全改变了......你能粘贴你的 WebApiConfig 类吗?

标签: c# authentication asp.net-web-api asp.net-mvc-5 asp.net-core-mvc


【解决方案1】:

TL;DR:你不能。

Authority 指的是 ASP.NET 5 中承载中间件中添加的 OpenID Connect 功能:在 OWIN/Katana 版本中没有这样的东西。

注意:Katana 有一个 app.UseJwtBearerAuthentication 扩展名,但与它的 ASP.NET 5 等效项不同,它不使用任何 OpenID Connect 功能并且必须手动配置:您必须提供颁发者名称和证书用于验证令牌的签名:https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.Jwt/JwtBearerAuthenticationExtensions.cs

【讨论】:

    【解决方案2】:

    您可以获得以下声明:

     IAuthenticationManager AuthenticationManager
     {
        get
        {
            return Request.GetOwinContext().Authentication;
        }
    }
    
    public IHttpActionResult UserRoles()
    {
     return ok(AuthenticationManager.User.Claims.ToList());
    }
    

    此代码应在 [Authorize] 控制器中。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 2021-10-27
      • 2015-09-19
      • 2015-07-23
      • 2016-09-06
      • 2016-07-13
      相关资源
      最近更新 更多