18 Improving your application’s security

This chapter covers

  • Encrypting traffic using HTTPS and configuring local SSL certificates
  • Defending against cross-site scripting attacks
  • Protecting from cross-site request forgery attacks
  • Allowing calls to your API from other apps using CORS

Web application security is a hot topic at the moment. Practically every week another breach is reported, or confidential details are leaked. It may seem like the situation is hopeless, but the reality is that the vast majority of breaches could’ve been avoided with the smallest amount of effort.

In this chapter, we look at a few different ways to protect your application and your application’s users from attackers. Because security is an extremely broad topic that covers lots of different avenues, this chapter is by no means an exhaustive guide. It’s intended to make you aware of some of the most common threats to your app and how to counteract them, and to highlight areas where you can inadvertently introduce vulnerabilities if you’re not careful.


I strongly advise exploring additional resources around security after you’ve read this chapter. The Open Web Application Security Project (OWASP) (www.owasp.org) is an excellent resource, though it can be a little dry. Alternatively, Troy Hunt (www.troyhunt.com/) has some excellent courses and workshops on security, geared towards .NET developers.

18.1  Adding HTTPS to an application

18.1.1    Using the .NET Core and IIS Express HTTPS development certificates

18.1.2    Configuring Kestrel with a production HTTPS certificate

18.1.3    Enforcing HTTPS for your whole app

18.2  Defending against cross-site scripting (XSS) attacks

18.3  Protecting from cross-site request forgery (CSRF) attacks

18.4  Calling your web APIs from other domains using CORS

18.4.1    Understanding CORS and how it works

18.4.2    Adding a global CORS policy to your whole app

18.4.3    Adding CORS to specific Web API actions with EnableCorsAttribute

18.4.4    Configuring CORS policies

18.5  Exploring other attack vectors

18.5.1    Detecting and avoiding open redirect attacks

18.5.2    Avoiding SQL injection attacks with EF Core and parameterization

18.5.3    Preventing insecure direct object references

18.5.4    Protecting your users’ passwords and data

18.6  Summary