首页 文章

使用带有MVC的OAuth承载令牌(JWT)

提问于
浏览
2

我创建了一个后端WebApi来创建JWT令牌,当我使用PostMan通过向令牌添加令牌来访问受限资源时,它们工作正常,例如[授权(角色= “超级管理员”)] .

我想在我的MVC应用程序中使用此基础结构,但不太清楚如何将它绑定在一起 .

我猜测当用户创建一个帐户并为他们生成一个JWT时(通过WebApi),我需要将令牌粘贴在cookie中,但是如何做到这一点并在未来的请求中从cookie中提取JWT,这样它将与我用ActionResults装饰的普通[Authorize]属性一起使用?

我是否需要在Owin管道中放置一些东西?或者我是否需要创建自定义[授权]属性?

我的Startup.cs文件目前看起来像这样:

public void Configuration(IAppBuilder app)
    {
        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);

        ConfigureOAuthTokenConsumption(app);


        ConfigureWebApi(httpConfig);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        app.UseWebApi(httpConfig);

    }

    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            //TODO: enforce https in live
            //For Dev enviroment only (on production should be AllowInsecureHttp = false)
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat = new CustomJwtFormat("https://localhost:443")
        };

        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here


        // OAuth 2.0 Bearer Access Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
    }

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {
        var issuer = "https://localhost:443";
        string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
        byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
    }

    private void ConfigureWebApi(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }

如果它有帮助,我正在遵循本指南:http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/

1 回答

  • 2

    您所引用的基础架构实际上是为处理直接Web API调用而设计的 . 基于经典重定向的Web应用程序将依赖于更传统的模式,其中应用程序接收一个令牌,验证它并使用它来启动经过身份验证的会话(通过在某些会话工件中保存令牌验证的结果,如令牌) . 虽然您可以从任何基于令牌的系统开始实现此模式,包括您的自定义系统,但通常利用现有协议(如OpenId Connect)和现有产品(如Azure AD或Identity Server)更方便(且更安全) . 有关基于Azure AD的简单示例,请参阅this - 无论您选择哪种OpenId提供程序,中间件都保持不变 .

相关问题