MVC-6与MVC-5在Web API中的承载认证

本文关键字:认证 API MVC-5 Web MVC-6 | 更新日期: 2023-09-27 18:12:50

我有一个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;
            }
}

我不能调用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返回声明到客户端应用程序。
谢谢你的帮助。

MVC-6与MVC-5在Web API中的承载认证

TL;博士:你不能。

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

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

您可以获得索赔:

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

此代码应该在[authorization]控制器中