如何在ASP .NET WebAPI中阻止对承载令牌的这种利用?

时间:2018-07-23 08:33:14

标签: c# asp.net-web-api oauth

服务器向我发送令牌,如下所示:

K_ZOMie5a2jZZ40UgwabpF9bvhrfDg4QNB4oiYcf-29J0cowj-pAuA4pSaEJzS5qo_yjXlpui8d65y-nVQXCHHbmu9H7CcHUOUHJzaE1dORjDBQyhNB5-4aZvBaoFj6258x1RTz2F-FoL1ZwFHBevTmz_TdG2EY2XdjOySbDeV7XlDQly_ruO_LqUbs3Of1Vxj4tEXrSKCdomObk7eu_5T1srwp2_5uL6broAjcWLtykS0hgaUi5JRMxkx0tHcAjGxu1p5O3BYCllHqWH0ver4T0-rPI0T_s3Yq0qZT3g41BM4frtf8oJ-KQYHFlqxp1fGfVi1vgYxLMTD9z-jNlJI9-EmBhd3raZH-ASkiLKPw_NV5U9hbpz_1Fym3XQVf2ll7NeUa8R5E-pE9dn-qNsllbQ3Dhpg6J3cFzNBbssZt0y_qId4gFIHaeaqIWZY19XHACcwjX971lgLTY2mIwqDaSuOqygiu4tAZChp8Syo_HuYoJBjsNY-Wrys8Il8glJixI-_FCQOUors3yApZrrA

我已将此令牌存储在Web应用程序上的javascript变量中,如果进行了检查,则可以从浏览器控制台轻松访问该令牌,并且Webapp可以访问api。 但是,如果我复制此令牌并粘贴到邮递员或任何其他客户端上,则可以访问受保护的资源。 如何防止这种利用?我想以某种方式在请求api之前验证令牌原始客户端

我的ConfigureOAuth代码:

public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };


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

        }

我的OAuthAutorizationProviderCode:

 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            if (context.ClientId == null)
            {
                context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
                context.Rejected();

                return;
            }
            try
            {
                // You're going to check the client's credentials on a database.
                if (clientId == "MyApp" && clientSecret == "MySecret")
                {
                    ApplicationClient client = new ApplicationClient();
                    client.Id = clientId;
                    client.AllowedGrant = OAuthGrant.ResourceOwner;
                    client.ClientSecretHash = new PasswordHasher().HashPassword("MySecret");
                    client.Name = "My App";
                    client.CreatedOn = DateTimeOffset.UtcNow;

                    context.OwinContext.Set<ApplicationClient>("oauth:client", client);
                    context.Validated(clientId);
                }
                else
                {
                    // Client could not be validated.
                    context.SetError("invalid_client", "Client credentials are invalid.");
                    context.Rejected();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                context.SetError("server_error");
                context.Rejected();
            }

            return;
        }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        ApplicationClient client = context.OwinContext.Get<ApplicationClient>("oauth:client");
 if (client.AllowedGrant != OAuthGrant.ResourceOwner)
            {
                context.SetError("invalid_grant", "The resource owner credentials are invalid or resource owner does not exist.");
                context.Rejected();
                return;
            }
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });


        SpLoginTsk_Result model = new SpLoginTsk_Result();
        model = this.acs.Login(context.UserName, context.Password);

        if (model==null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }


        var identity = new ClaimsIdentity(new[]
        {   new System.Security.Claims.Claim(ClaimTypes.Name, model.PersonId.ToString()),
            new System.Security.Claims.Claim(ClaimTypes.Role,model.RoleId.ToString())
        }, "ApplicationCookie", ClaimTypes.Name, ClaimTypes.Role

        );
        AuthenticationProperties properties = CreateAuthenticationProperties(model);//Dictionary used to store state values about the authentication session.
        AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);//Contains user identity information as well as additional authentication state.

        context.Validated(ticket);//Replaces the ticket information on this context and marks it as as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling
        context.Request.Context.Authentication.SignIn(identity);
    }
    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

0 个答案:

没有答案