# Security

{% embed url="https://learn.microsoft.com/en-us/aspnet/core/security/" %}

## Authentication vs. Authorization <a href="#authentication-vs-authorization" id="authentication-vs-authorization"></a>

**Authentication** is a process in which a user provides credentials that are then compared to those stored in an operating system, database, app or resource. If they match, users authenticate successfully, and can then perform actions that they're authorized for, during an authorization process. The **Authorization** refers to the process that determines what a user is allowed to do.

| Authentication                                                   | Authorization                                                                                                    |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Authentication is the process of determining a user's identity.  | Authorization is the process of determining whether a user has access to a resource.                             |
|                                                                  | <ul><li>role-based authorization</li><li>policy-based authorization</li><li>claims-based authorization</li></ul> |

## CORS

**Cross-Origin Resource Sharing** is an [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.&#x20;

> Is **not** a security feature, CORS relaxes security. An API is not safer by allowing CORS.

There are three ways to enable CORS:

* In middleware using a **named policy** or **default policy**.

<pre class="language-csharp"><code class="lang-csharp"><strong>var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
</strong>
var builder = WebApplication.CreateBuilder(args);
<strong>builder.Services.AddCors(options => {                
</strong><strong>    options.AddPolicy(name: MyAllowSpecificOrigins, policy => { // named policy
</strong><strong>            policy.WithOrigins("http://example.com", "http://www.contoso.com")
</strong><strong>                    .AllowAnyHeader()
</strong><strong>                    .AllowAnyMethod();
</strong><strong>    }); 
</strong>     
<strong>    options.AddDefaultPolicy(policy => {        // default policy
</strong><strong>            policy.WithOrigins("http://example.com", "http://www.contoso.com");
</strong><strong>    });  
</strong><strong>});
</strong>
// services.AddResponseCaching();
builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

<strong>app.UseCors(MyAllowSpecificOrigins);        // using named policy
</strong>
app.UseAuthorization();

app.MapControllers();

app.Run();
</code></pre>

* Using **endpoint routing**.

<pre class="language-csharp"><code class="lang-csharp">var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options => {
    options.AddPolicy(name: MyAllowSpecificOrigins, policy => {
        policy.WithOrigins("http://example.com", "http://www.contoso.com");
    });
});

builder.Services.AddControllers();
builder.Services.AddRazorPages();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/echo",
        context => context.Response.WriteAsync("echo"))
<strong>        .RequireCors(MyAllowSpecificOrigins);
</strong>
    endpoints.MapControllers()
<strong>             .RequireCors(MyAllowSpecificOrigins);
</strong>
    endpoints.MapGet("/echo2",
        context => context.Response.WriteAsync("echo2"));

    endpoints.MapRazorPages();
});

app.Run();
</code></pre>

* With the `[EnableCors]` attribute.

```csharp
[Route("api/[controller]")]
[ApiController]
public class WidgetController : ControllerBase
{
    // GET api/values
    [EnableCors("AnotherPolicy")]
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "green widget", "red widget" };
    }
}
```

{% hint style="info" %}
Using the [\[EnableCors\]](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0#attr) attribute with a named policy provides the finest control in limiting endpoints that support CORS.
{% endhint %}

{% hint style="info" %}
When using multiple roles in one attribute, the user must be a member of only one of those roles to access the resource. With multiple attributes, the user must be a member of all roles.
{% endhint %}

When you implement `IValidateObject`, which language feature processes over the individual properties being validated?

* C# Generator/Yield pattern
