Skip to content

Commit dbdafb5

Browse files
web security updates ProfessionalCSharp#46
1 parent 46b80d4 commit dbdafb5

File tree

84 files changed

+28334
-11648
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

84 files changed

+28334
-11648
lines changed

02_Libs/Security/ASPNETCoreMVCSecurity/.bowerrc

-3
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
1-
<Project Sdk="Microsoft.NET.Sdk.Web">
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp2.1</TargetFramework>
4+
<TargetFramework>net5.0</TargetFramework>
5+
<Nullable>enable</Nullable>
56
</PropertyGroup>
67

78
<ItemGroup>
8-
<PackageReference Include="Microsoft.AspNetCore.All" />
9-
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design">
10-
<Version>2.1.7</Version>
11-
</PackageReference>
12-
</ItemGroup>
13-
14-
<ItemGroup>
15-
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
9+
<PackageReference Include="Microsoft.Data.SqlClient" Version="2.1.2" />
10+
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
1611
</ItemGroup>
1712

1813
</Project>
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,83 @@
1-
using System;
1+
using ASPNETCoreMVCSecurity.Models;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.Data.SqlClient;
4+
using Microsoft.Extensions.Configuration;
5+
using Microsoft.Extensions.Logging;
6+
using System;
27
using System.Collections.Generic;
38
using System.Diagnostics;
49
using System.Linq;
10+
using System.Text;
511
using System.Threading.Tasks;
6-
using Microsoft.AspNetCore.Mvc;
7-
using ASPNETCoreMVCSecurity.Models;
8-
using Microsoft.AspNetCore.Html;
9-
using System.Net.Http.Headers;
1012

1113
namespace ASPNETCoreMVCSecurity.Controllers
1214
{
1315
public class HomeController : Controller
1416
{
15-
public string Echo(string x) => x;
17+
private readonly ILogger<HomeController> _logger;
18+
private readonly IConfiguration _settings;
1619

17-
public IActionResult EchoUnencoded(string x) => Content(x, "text/html");
18-
19-
public IActionResult EchoWithView(string x)
20+
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
2021
{
21-
ViewBag.SampleData = x;
22-
return View();
22+
_logger = logger;
23+
_settings = configuration;
2324
}
2425

2526
public IActionResult Index()
2627
{
2728
return View();
2829
}
2930

30-
public IActionResult About()
31+
public IActionResult Privacy()
3132
{
32-
ViewData["Message"] = "Your application description page.";
33-
3433
return View();
3534
}
3635

37-
public IActionResult Contact()
38-
{
39-
ViewData["Message"] = "Your contact page.";
36+
public string Echo(string x) => x;
4037

38+
public IActionResult EchoUnencoded(string x) => Content(x, "text/html");
39+
40+
public IActionResult EchoWithView(string x)
41+
{
42+
ViewBag.SampleData = x;
4143
return View();
4244
}
4345

44-
public IActionResult Error()
46+
public IActionResult SqlSample(string id)
4547
{
46-
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
48+
string connectionString = _settings.GetConnectionString("InjectionConnection");
49+
SqlConnection sqlConnection = new(connectionString);
50+
SqlCommand command = sqlConnection.CreateCommand();
51+
52+
// don't do this - string concatenation for SQL commands!
53+
command.CommandText = "SELECT * FROM Customers WHERE City = " + id;
54+
sqlConnection.Open();
55+
using SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
56+
57+
StringBuilder sb = new();
58+
while (reader.Read())
59+
{
60+
for (int i = 0; i < reader.FieldCount; i++)
61+
{
62+
sb.Append(reader[i]);
63+
}
64+
sb.AppendLine();
65+
}
66+
ViewBag.Data = sb.ToString();
67+
68+
return View();
4769
}
4870

4971
public IActionResult EditBook() => View();
5072

5173
[HttpPost]
52-
// [ValidateAntiForgeryToken]
5374
public IActionResult EditBook(Book book) => View("EditBookResult", book);
75+
76+
77+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
78+
public IActionResult Error()
79+
{
80+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
81+
}
5482
}
5583
}
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
6-
namespace ASPNETCoreMVCSecurity.Models
1+
namespace ASPNETCoreMVCSecurity.Models
72
{
8-
public class Book
9-
{
10-
public string Title { get; set; }
11-
public string Publisher { get; set; }
12-
}
3+
public record Book(string Title, string? Publisher);
4+
135
}

02_Libs/Security/ASPNETCoreMVCSecurity/Models/ErrorViewModel.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ public class ErrorViewModel
88

99
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
1010
}
11-
}
11+
}
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
using Microsoft.AspNetCore;
21
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Hosting;
33

44
namespace ASPNETCoreMVCSecurity
55
{
66
public class Program
77
{
88
public static void Main(string[] args)
99
{
10-
BuildWebHost(args).Run();
10+
CreateHostBuilder(args).Build().Run();
1111
}
1212

13-
public static IWebHost BuildWebHost(string[] args) =>
14-
WebHost.CreateDefaultBuilder(args)
15-
.UseStartup<Startup>()
16-
.Build();
13+
public static IHostBuilder CreateHostBuilder(string[] args) =>
14+
Host.CreateDefaultBuilder(args)
15+
.ConfigureWebHostDefaults(webBuilder =>
16+
{
17+
webBuilder.UseStartup<Startup>();
18+
});
1719
}
1820
}
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
{
1+
{
22
"iisSettings": {
33
"windowsAuthentication": false,
44
"anonymousAuthentication": true,
55
"iisExpress": {
6-
"applicationUrl": "http://localhost:48985/",
7-
"sslPort": 0
6+
"applicationUrl": "http://localhost:60555",
7+
"sslPort": 44391
88
}
99
},
1010
"profiles": {
@@ -17,11 +17,12 @@
1717
},
1818
"ASPNETCoreMVCSecurity": {
1919
"commandName": "Project",
20+
"dotnetRunMessages": "true",
2021
"launchBrowser": true,
22+
"applicationUrl": "https://localhost:5001;http://localhost:5000",
2123
"environmentVariables": {
2224
"ASPNETCORE_ENVIRONMENT": "Development"
23-
},
24-
"applicationUrl": "http://localhost:48989/"
25+
}
2526
}
2627
}
27-
}
28+
}

02_Libs/Security/ASPNETCoreMVCSecurity/Startup.cs

+16-16
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
using Microsoft.AspNetCore.Builder;
1+
using Microsoft.AspNetCore.Builder;
22
using Microsoft.AspNetCore.Hosting;
33
using Microsoft.AspNetCore.Http;
44
using Microsoft.Extensions.Configuration;
55
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Hosting;
67
using System.Text.Encodings.Web;
78

89
namespace ASPNETCoreMVCSecurity
@@ -19,47 +20,46 @@ public Startup(IConfiguration configuration)
1920
// This method gets called by the runtime. Use this method to add services to the container.
2021
public void ConfigureServices(IServiceCollection services)
2122
{
22-
services.AddMvc();
23+
services.AddControllersWithViews();
2324
}
2425

2526
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
26-
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
27+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2728
{
2829
if (env.IsDevelopment())
2930
{
3031
app.UseDeveloperExceptionPage();
31-
app.UseBrowserLink();
3232
}
3333
else
3434
{
3535
app.UseExceptionHandler("/Home/Error");
36+
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
37+
app.UseHsts();
3638
}
37-
39+
app.UseHttpsRedirection();
3840
app.UseStaticFiles();
3941

40-
app.Map("/echo", app1 =>
42+
app.UseRouting();
43+
44+
app.UseAuthorization();
45+
46+
app.UseEndpoints(endpoints =>
4147
{
42-
app1.Run(async context =>
48+
endpoints.Map("/echo", async context =>
4349
{
4450
string data = context.Request.Query["x"];
4551
await context.Response.WriteAsync(data);
4652
});
47-
});
4853

49-
app.Map("/echoenc", app1 =>
50-
{
51-
app1.Run(async context =>
54+
endpoints.Map("/echoenc", async context =>
5255
{
5356
string data = context.Request.Query["x"];
5457
await context.Response.WriteAsync(HtmlEncoder.Default.Encode(data));
5558
});
56-
});
5759

58-
app.UseMvc(routes =>
59-
{
60-
routes.MapRoute(
60+
endpoints.MapControllerRoute(
6161
name: "default",
62-
template: "{controller=Home}/{action=Index}/{id?}");
62+
pattern: "{controller=Home}/{action=Index}/{id?}");
6363
});
6464
}
6565
}

02_Libs/Security/ASPNETCoreMVCSecurity/Views/Home/About.cshtml

-7
This file was deleted.

02_Libs/Security/ASPNETCoreMVCSecurity/Views/Home/Contact.cshtml

-17
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,16 @@
1-
@using Microsoft.AspNetCore.Html;
1+
22
@{
3-
Layout = null;
3+
string data = ViewBag.SampleData;
44
}
5+
<h3>
6+
This is encoded
7+
</h3>
8+
<div>@data</div>
59

6-
<!DOCTYPE html>
7-
8-
<html>
9-
<head>
10-
<meta name="viewport" content="width=device-width" />
11-
<title>EchoWithView</title>
12-
</head>
13-
<body>
14-
@{
15-
string data = ViewBag.SampleData;
16-
}
17-
<div>
18-
this is encoded
19-
</div>
20-
<div>@data</div>
21-
22-
<br />
23-
<div>
24-
This is not encoded
25-
</div>
26-
<div>
27-
@Html.Raw(@data)
28-
</div>
29-
30-
31-
</body>
32-
</html>
10+
<br />
11+
<h3>
12+
This is not encoded
13+
</h3>
14+
<div>
15+
@Html.Raw(@data)
16+
</div>

02_Libs/Security/ASPNETCoreMVCSecurity/Views/Home/EditBook.cshtml

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,10 @@
22
@{
33
ViewData["Title"] = "EditBook";
44
}
5-
<h2>Edit Book</h2>
65

6+
<h1>EditBook</h1>
77

88
<form asp-controller="Home" asp-action="EditBook" method="post">
9-
// @Html.AntiForgeryToken()
10-
119
<label for="title">Title:</label>
1210
<input type="text" id="title" name="title" />
1311
<br />
@@ -16,3 +14,5 @@
1614
<br />
1715
<input type="submit" value="Submit" />
1816
</form>
17+
18+

02_Libs/Security/ASPNETCoreMVCSecurity/Views/Home/EditBookResult.cshtml

-9
This file was deleted.

0 commit comments

Comments
 (0)