title
stringlengths
3
46
content
stringlengths
0
1.6k
21:1526
ViewData[`ReturnUrl`] = returnUrl;
21:1527
return View();
21:1528
}
21:1529
21:1530
It receives returnUrl as its parameter when the browser is automatically redirected to the login page by the authorization module. This happens when an unlogged-in user tries to access a protected page. returnUrl is stored in the ViewState dictionary that is passed to the login view.
21:1531
The form in the login view passes it back to the controller, together with the username and password when it is submitted, as shown in this code:
21:1532
<form asp-route-returnurl=`@ViewData[`ReturnUrl`]` method=`post`>
21:1533
...
21:1534
</form>
21:1535
21:1536
The form post is intercepted by an action method with the same Login name but decorated with the [HttpPost] attribute, as shown here:
21:1537
[ValidateAntiForgeryToken]
21:1538
public async Task<IActionResult> Login(
21:1539
LoginViewModel model,
21:1540
string? returnUrl = null)
21:1541
{
21:1542
...
21:1543
21:1544
The preceding method receives the Login model used by the login view, together with the returnUrl query string parameter. The ValidateAntiForgeryToken attribute verifies a token (called an anti-forgery token) that MVC forms automatically. This is then added to a hidden field to prevent XSRF/CSRF attacks.
21:1545
21:1546
Forgery attacks exploit authentication cookies stored in the victim’s browser to submit a legitimate authenticated request to a web application. They do this by inducing the user to click a button on a phishing website that causes a submit to the target web application. The fraudulent request is accepted since, once a form is submitted, the authentication cookies for the target URL are automatically sent by the browser. There are just two defenses against this kind of attack:
21:1547
21:1548
Authentication cookies are defined as same-origin – that is, they are sent from other domains just in case of GET requests. Thus, when a form is submitted from a phishing website to the target application, they are not sent.
21:1549
Anti-forgery tokens added to forms. In this case, if authentication cookies are sent together with the submitted form, the application understands that the request comes from a different website and blocks it since it is missing a valid anti-forgery token.
21:1550
21:1551
21:1552
As a first step, the action method logs the user out if they are already logged in:
21:1553
if (User.Identity.IsAuthenticated)
21:1554
{
21:1555
await signInManager.SignOutAsync();
21:1556
21:1557
}
21:1558
21:1559
Otherwise, it verifies whether there are validation errors, in which case, it shows the same view filled with the data of the ViewModel to let the user correct their errors:
21:1560
if (ModelState.IsValid)
21:1561
{
21:1562
...
21:1563
}
21:1564
else
21:1565
// If we got this far, something failed, redisplay form
21:1566
return View(model);
21:1567
21:1568
If the model is valid, signInManager is used to log the user in:
21:1569
var result = await signInManager.PasswordSignInAsync(
21:1570
model.UserName,
21:1571
model.Password, model.RememberMe,
21:1572
lockoutOnFailure: false);
21:1573
21:1574
If the result returned by the operation is successful, the action method redirects the browser to returnUrl if it’s not null; otherwise, it redirects the browser to the home page:
21:1575
if (result.Succeeded)
21:1576
{
21:1577
if (!string.IsNullOrEmpty(returnUrl))
21:1578
return LocalRedirect(returnUrl);
21:1579
else
21:1580
return RedirectToAction(nameof(HomeController.Index), `Home`);
21:1581
}
21:1582
else
21:1583
{
21:1584
ModelState.AddModelError(string.Empty,
21:1585
`wrong username or password`);
21:1586
return View(model);
21:1587
}
21:1588
21:1589
If the login fails, it adds an error to ModelState and shows the same form to let the user try again.
21:1590
ManagePackagesController contains an Index method that shows all packages in table format (for more details on controllers, views, and the MVC pattern in general, please refer to the The MVC pattern section of Chapter 17, Presenting ASP.NET Core):
21:1591
[HttpGet]
21:1592
public async Task<IActionResult> Index(
21:1593
[FromServices] IPackagesListQuery query)
21:1594
{
21:1595
var results = await query.GetAllPackages();
21:1596
var vm = new PackagesListViewModel { Items = results };
21:1597
return View(vm);
21:1598
}
21:1599
21:1600
The query object is injected into the action method by DI. Then, the action method invokes it and inserts the resulting IEnumerable into the Items property of a PackagesListViewModel instance. It is a good practice to include IEnumerables in ViewModels instead of passing them directly to the views so that, if necessary, other properties can be added without the need to modify the existing view code.
21:1601
Moreover, it is good practice to define enumerable properties of ViewModels as IReadOnlyCollection<T> if the enumerables are read-only or as IList<T> if the enumerables can be modified or if they are involved in model binding. In fact, ICollection<T> has a Count property, which may be very useful when rendering ViewModels in views, while IList<T> also has indexers that are necessary for rendering all items with appropriate names for model binding to succeed (see this Phil Haack post: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx). IEnumerable<T> should be preferred only in the case that one needs the typical lazy evaluation of IEnumerable<T>.
21:1602
The results are shown in a Bootstrap table since Bootstrap CSS is automatically scaffolded by Visual Studio. Bootstrap is a good choice for a CSS framework, since it is quite simple and extensible, and is not connected to any particular company but is handled by an independent team.
21:1603
The result is shown here:
21:1604
21:1605
Figure 21.29: Application packages handling page
21:1606
The New package link (it is shaped like a Bootstrap button, but it is a link) invokes a controller Create action method, while the delete and edit links in each row invoke a Delete and Edit action method, respectively, and pass them the ID of the package shown in the row.
21:1607
Here is the implementation of the two row links:
21:1608
@foreach(var package in Model.Items)
21:1609
{
21:1610
<tr>
21:1611
<td>
21:1612
<a asp-controller=`ManagePackages`
21:1613
asp-action=`@nameof(ManagePackagesController.Delete)`
21:1614
asp-route-id=`@package.Id`>
21:1615
delete
21:1616
</a>
21:1617
</td>
21:1618
<td>
21:1619
<a asp-controller=`ManagePackages`
21:1620
asp-action=`@nameof(ManagePackagesController.Edit)`
21:1621
asp-route-id=`@package.Id`>
21:1622
edit
21:1623
</a>
21:1624
</td>
21:1625
...