stefanprodan / WebApiThrottle

ASP.NET Web API rate limiter for IIS and Owin hosting
MIT License
1.28k stars 274 forks source link

expect an example about oauth #76

Closed seven1986 closed 7 years ago

seven1986 commented 8 years ago

Thanks a lot When client got accessToken they do need appkey with any request, So how can I limit the request before valiate accessToken? I am going to use it in my product envirment, so could you help me? thanks

stefanprodan commented 7 years ago

When a user is authorize, you'll have to add a claim to the identity store, like userId or whatever you use to uniquely identify your clients. Then you can override the ThrottlingMiddleware.SetIdentity function and use that claim as the throttle key. Something like this:

public class OAuthThrottlingMiddleware : ThrottlingMiddleware
{
    protected override RequestIdentity SetIdentity(IOwinRequest request)
    {
          var userId = "anon";
         if(request.Context.User.Identity.IsAuthenticated)
         {
            //get userId from identity claim 
         }
        return new RequestIdentity()
        {
            ClientKey = userId,
            ClientIp = base.GetClientIp(request).ToString(),
            Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()
        };
    }
}
seven1276 commented 7 years ago

Thanks,It works,fantastic! And must put this code app.Use<OAuthThrottlingMiddleware>(); after app.use OAuth API

One more question I want to know is about image

SetIdentity does not excute when I write 'base.PolicyRepository = new PolicyMemoryCacheRepository()'

stefanprodan commented 7 years ago

Remove that constructor and build your Policy outside the OAuthThrottlingMiddleware:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var oauthPolicy = BuildPolicyFromDB();

        appBuilder.Use(typeof(OAuthThrottlingMiddleware),
            oauthPolicy,
            new PolicyMemoryCacheRepository(),
            new MemoryCacheRepository(),
            null,
            null);
    }
}