MVC-6与MVC-5 Web API中的Bearer身份验证对比

14

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

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项目中实现相同的功能。我尝试过类似于以下代码:

Web API:

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;
            }
}

如果设置了[authorized]属性,我无法调用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中的索赔返回给客户端应用程序。使用Bearer身份验证。
感谢帮助。


我在哪里可以找到 app.UseJwtBearerAuthentication(...) ?你的 project.json 和使用引用(在 Startup.cs 中)是什么样子的? - Mickael Caruso
"Microsoft.AspNet.Authentication.JwtBearer":"1.0.0-*" - Raskolnikov
在启动代码未被调用时,您可能需要一组符合MVC5标准的NuGet依赖项。我建议您使用Global.asax.cs中的Application_Start方法,而不是OwinStartup - user326608
你安装了Web主机包吗?需要Microsoft.Owin.Host.SystemWeb - 例如:https://dev59.com/o2Ij5IYBdhLWcg3wflIy - Dylan Morley
看起来问题已经完全改变了...你能粘贴你的WebApiConfig类吗? - Kévin Chalet
2个回答

7
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

0

您可以获取以下声明:

 IAuthenticationManager AuthenticationManager
 {
    get
    {
        return Request.GetOwinContext().Authentication;
    }
}

public IHttpActionResult UserRoles()
{
 return ok(AuthenticationManager.User.Claims.ToList());
}

这段代码应该在 [Authorize] 控制器中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接