Ways to secure an anonymous Web API request

后端 未结 3 1920
予麋鹿
予麋鹿 2021-02-02 09:29

I have a ASP.NET MVC (NOT ASP.NET Core) single page application with angular js on the front end.

My client (browser) talks to server

3条回答
  •  广开言路
    2021-02-02 10:24

    I also once had the weird need for having session functionality on WebAPI and created an OWIN Session middleware that does exactly what you're aiming for.

    The library is called OwinSessionMiddleware and is available on github and NuGet.

    Usage

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseSessionMiddleware();
    
            // other middleware registrations...
            app.UseWebApi();
        }
    }
    

    You can also pass some options to further tweak cookie-name, add a database backed session store (instead of in-memory), add your own session id generator (instead of default id generator which is based on GUID + secure random part generated by RNGCryptoServiceProvider).

    The unique session id itself is stored as a secure cookie and the session is restored automatically by the middleware on each request.

    There are extension methods you can call inside your API controller to get and set session data:

    public SomeApiController : ApiController
    {
        public IHttpActionResult MyAction()
        {
            var requestCount = Request.GetSessionProperty("RequestCount");
    
            Request.SetSessionProperty("RequestCount", ++requestCount);
        }
    }
    

提交回复
热议问题