MVC POST请求丢失授权标头 - 如何在检索后使用API​​承载标记

Chr*_*son 7 post asp.net-authorization oauth-2.0 asp.net-mvc-5 asp.net-web-api2

我花了最后一周为现有的MVC应用程序创建API,现在我正在尝试保护API以及根据需要重新修改MVC端安全性.

目前,MVC应用程序设置为通过OWIN/OAuth/Identity使用应用程序cookie.我试图合并设置Web API的Bearer令牌,以便在调用受限API方法时生成,但到目前为止收效甚微 - GET请求工作正常,但POST请求在收到时失去了Authorization标头. API.

我已经创建了一个SDK客户端,MVC应用程序正在使用它来调用API,并尝试了三种为API的任何给定调用设置Authorization标头的方法,所有这些方法似乎都能正常工作对于GET请求很好,但是对于我需要做的任何POST请求完全失败...

我可以在MVC控制器中设置Request标头:

HttpContext.Request.Headers.Add("授权","承载"+ response.AccessToken);

(其中response.AccessToken是先前从API检索的令牌)
我可以通过SDK客户端上的扩展方法设置Request头:

_apiclient.SetBearerAuthentication(token.AccessToken)

或者我可以在SDK客户端上手动设置Request标头:

_apiClient.Authentication = new AuthenticationHeaderValue("Bearer,accessToken);

(其中accessToken是先前检索的令牌,传递给被调用的Client方法).

从这一点来看,我几乎没有什么可以解决导致这个问题的原因.到目前为止,我唯一能够收集的是ASP.NET导致所有POST请求首先发送请求,并带有Expect标头,用于HTTP 100-Continue响应,之后它将完成实际的POST请求.但是,似乎当它执行第二次请求时,Authorization标头不再存在,因此API的Authorize属性将导致401-Unauthorized响应,而不是实际运行API方法.

那么,我如何获取能够从API检索的Bearer令牌,并在后续请求中使用它,包括我需要做的各种POST请求?

除此之外,将此令牌存储在MVC应用程序本身的最佳方法是什么?我宁愿避免将字符串传递给应用程序中可能需要它的每个方法,但我也一直在阅读,出于安全原因将其存储在cookie中是一个非常糟糕的主意.

在我通过这个问题后,我会立即感兴趣的几点:

使用OAuth Bearer Tokens是否意味着我不能再将ApplicationCookies用于MVC应用程序?和/或它会在整个应用程序中使以下代码无用吗?

User.Identity.GetUserId()

目前我被迫评论我的API [授权]属性以继续我的工作,这显然不是理想的但它确实允许我暂时继续处理.

启动文件:

MVC:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    private void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ADUIdentityDbContext.Create);
        app.CreatePerOwinContext<ADUUserManager>(ADUUserManager.Create);

        app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                                 {
                                     AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                                     //This should be set to FALSE before we move to production.
                                     AllowInsecureHttp =  true,
                                     ApplicationCanDisplayErrors = true,
                                     TokenEndpointPath = new PathString("/api/token"),

                                 });

        app.UseCookieAuthentication(new CookieAuthenticationOptions
                                    {
                                        AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                                        CookieName = "ADU",
                                        ExpireTimeSpan = TimeSpan.FromHours(2),
                                        LoginPath = new PathString("/Account/Login"),
                                        SlidingExpiration = true,

                                    });
    }
}
Run Code Online (Sandbox Code Playgroud)

API

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        config.DependencyResolver = new NinjectResolver(new Ninject.Web.Common.Bootstrapper().Kernel);

        WebApiConfig.Register(config);

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

        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ADUIdentityDbContext.Create);
        app.CreatePerOwinContext<ADUUserManager>(ADUUserManager.Create);

        OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider(),
        };

        //token generation
        app.UseOAuthAuthorizationServer(oAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}
Run Code Online (Sandbox Code Playgroud)


public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    private IUserBusinessLogic _userBusinessLogic;

    /// <summary>
    /// Creates the objects necessary to initialize the user business logic field and initializes it, as this cannot be done by dependency injection in this case.
    /// </summary>
    public void CreateBusinessLogic()
    {
        IUserRepository userRepo = new UserRepository();
        IGeneratedExamRepository examRepo = new GeneratedExamRepository();
        IGeneratedExamBusinessLogic examBLL = new GeneratedExamBusinessLogic(examRepo);
        _userBusinessLogic = new UserBusinessLogic(userRepo, examBLL);
    }

    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[] { "*" });

        //create a claim for the user
        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", user.Id));
        context.Validated(identity);
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*son 2

在花费大量时间处理项目的其他方面之后,实现其他功能实际上使解决这个问题变得更加容易 - 现在有一个响应包装处理程序作为 API 的一部分,并且该处理程序的一部分保存传入请求中的所有标头并将它们添加到传出的响应中。我相信这允许应用程序的 ASP.NET MVC 端在最初发送 200-OK 请求后再次发送授权标头。

我已经修改了我的身份验证以便利用角色,但我将尝试排除该代码,因为它不应与此处相关:

MVC Startup.cs:

    public class Startup
    {
        public void Configuration(IAppBuilder app) { ConfigureAuth(app); }

        /// <summary>
        ///     Configures authentication settings for OAuth.
        /// </summary>
        /// <param name="app"></param>
        private void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ADUIdentityDbContext.Create);
            app.CreatePerOwinContext<ADUUserManager>(ADUUserManager.Create);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
                                        {
                                            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                                            CookieName = "ADU",
                                            ExpireTimeSpan = TimeSpan.FromHours(2),
                                            LoginPath = new PathString("/Account/Login"),
                                            SlidingExpiration = true
                                        });
        }
    }
Run Code Online (Sandbox Code Playgroud)

使用位置(AccountController):

    private async Task CreateLoginCookie(AuthorizationToken response, User result)
        {
            //Create the claims needed to log a user in 
            //(uses UserManager several layers down in the stack)
            ClaimsIdentity cookieIdent = await _clientSDK.CreateClaimsIdentityForUser(response.AccessToken, result, true).ConfigureAwait(false);

            if (cookieIdent == null) throw new NullReferenceException("Failed to create claims for cookie.");
            cookieIdent.AddClaim(new Claim("AuthToken", response.AccessToken));

            AuthenticationProperties authProperties = new AuthenticationProperties();
            authProperties.AllowRefresh = true;
            authProperties.IsPersistent = true;
            authProperties.IssuedUtc = DateTime.Now.ToUniversalTime();

            IOwinContext context = HttpContext.GetOwinContext();
            AuthenticateResult authContext = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

            if (authContext != null)
                context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(cookieIdent, authContext.Properties);

            //Wrapper methods for IOwinContext.Authentication.SignOut()/SignIn()
            SignOut();
            SignIn(authProperties, cookieIdent);
        }
Run Code Online (Sandbox Code Playgroud)

在我的 SDK 层中,我创建了一个方法,从用于访问 API 的各种其他方法中调用该方法,以便为每个传出请求设置授权(我想弄清楚如何将其设为属性,但是我稍后会担心这个):

    private void SetAuthentication()
        {
            ClaimsIdentity ident = (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
            Claim claim;
            //Both of these methods (Thread.CurrentPrincipal, and ClaimsPrincipal.Current should work,
            //leaving both in for the sake of example.
            try
            {
                claim = ident.Claims.First(x => x.Type == "AuthToken");
            }
            catch (Exception)
            {
                claim = ClaimsPrincipal.Current.Claims.First(x => x.Type == "AuthToken");
            }
            
            _apiClient.SetBearerAuthentication(claim.Value);
        }
Run Code Online (Sandbox Code Playgroud)

API启动.cs

        /// <summary>
        ///     Configures the settings used by the framework on application start.  Dependency Resolver, OAuth, Routing, and CORS
        ///     are configured.
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            config.DependencyResolver = new NinjectResolver(new Bootstrapper().Kernel);

            WebApiConfig.Register(config);

            ConfigureOAuth(app);
            app.UseCors(CorsOptions.AllowAll);

            app.UseWebApi(config);
        }

        /// <summary>
        ///     Configures authentication options for OAuth.
        /// </summary>
        /// <param name="app"></param>
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ADUIdentityDbContext.Create);
            app.CreatePerOwinContext<ADUUserManager>(ADUUserManager.Create);

            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions
                                                                 {
                                                                     AllowInsecureHttp = true,
                                                                     TokenEndpointPath = new PathString("/api/token"),
                                                                     AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                                                                     Provider = new SimpleAuthorizationServerProvider()
                                                                 };

            //token generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

SimpleAuthorizationServerProvider.cs:

    /// <summary>
        ///     Creates an access bearer token and applies custom login validation logic to prevent invalid login attempts.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            // Performs any login logic required, such as accessing Active Directory and password validation.
            User user = await CustomLoginLogic(context).ConfigureAwait(false);

            //If a use was not found, add an error if one has not been added yet
            if((user == null) && !context.HasError) SetInvalidGrantError(context);

            //Break if any errors have been set.
            if (context.HasError) return;

            //create a claim for the user
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);

            //Add some basic information to the claim that will be used for the token.
            identity.AddClaim(new Claim("Id", user?.Id));
            identity.AddClaim(new Claim("TimeOf", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString()));

            //Roles auth
            SetRoleClaim(user, ref identity);

            context.Validated(identity);
        }
Run Code Online (Sandbox Code Playgroud)

最后,将所有内容包装在一起的明显关键:

    public class ResponseWrappingHandler : DelegatingHandler
    {
        /// <summary>
        /// Catches the request before processing is completed and wraps the resulting response in a consistent response wrapper depending on the response returned by the api.
        /// </summary>
        /// <param name="request">The request that is being processed.</param>
        /// <param name="cancellationToken">A cancellation token to cancel the processing of a request.</param>
        /// <returns></returns>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            //Calls Wrapping methods depending on conditions,
            //All of the Wrapping methods will make a call to PreserveHeaders()
        }

        /// <summary>
        /// Creates a response based on the provided request with the provided response's status code and request headers, and the provided response data.
        /// </summary>
        /// <param name="request">The original request.</param>
        /// <param name="response">The reqsponse that was generated.</param>
        /// <param name="responseData">The data to include in the wrapped response.</param>
        /// <returns></returns>
        private static HttpResponseMessage PreserveHeaders(HttpRequestMessage request, HttpResponseMessage response, object responseData)
        {
            HttpResponseMessage newResponse = request.CreateResponse(response.StatusCode, responseData);

            foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers)
                newResponse.Headers.Add(header.Key, header.Value);

            return newResponse;
        }
Run Code Online (Sandbox Code Playgroud)

完成所有这些后,我的项目现在可以使用授权/身份验证,而无需客户端机密等(这是我雇主的目标之一)。