|
1 | 1 | using Microsoft.AspNetCore.Mvc; |
2 | 2 | using Microsoft.AspNetCore.Authorization; |
| 3 | +using System.Threading.Tasks; |
| 4 | + |
| 5 | +public class CommentController : Controller |
| 6 | +{ |
| 7 | + private readonly IAuthorizationService _authorizationService; |
| 8 | + |
| 9 | + public CommentController(IAuthorizationService authorizationService) |
| 10 | + { |
| 11 | + _authorizationService = authorizationService; |
| 12 | + } |
3 | 13 |
|
4 | | -public class CommentController : Controller { |
5 | 14 | // BAD: Any user can access this. |
6 | | - public ActionResult Edit1(int commentId, string text) { |
| 15 | + public ActionResult Edit1(int commentId, string text) |
| 16 | + { |
7 | 17 | editComment(commentId, text); |
8 | 18 | return View(); |
9 | 19 | } |
10 | 20 |
|
11 | 21 | // GOOD: The user's authorization is checked. |
12 | | - public ActionResult Edit2(int commentId, string text) { |
13 | | - if (canEditComment(commentId, User.Identity.Name)){ |
| 22 | + public ActionResult Edit2(int commentId, string text) |
| 23 | + { |
| 24 | + if (canEditComment(commentId, User.Identity.Name)) |
| 25 | + { |
14 | 26 | editComment(commentId, text); |
15 | 27 | } |
16 | 28 | return View(); |
17 | 29 | } |
18 | 30 |
|
19 | 31 | // GOOD: The Authorize attribute is used |
20 | 32 | [Authorize] |
21 | | - public ActionResult Edit3(int commentId, string text) { |
| 33 | + public ActionResult Edit3(int commentId, string text) |
| 34 | + { |
22 | 35 | editComment(commentId, text); |
23 | 36 | return View(); |
24 | 37 | } |
25 | 38 |
|
26 | 39 | // BAD: The AllowAnonymous attribute overrides the Authorize attribute |
27 | 40 | [Authorize] |
28 | 41 | [AllowAnonymous] |
29 | | - public ActionResult Edit4(int commentId, string text) { |
| 42 | + public ActionResult Edit4(int commentId, string text) |
| 43 | + { |
| 44 | + editComment(commentId, text); |
| 45 | + return View(); |
| 46 | + } |
| 47 | + |
| 48 | + // GOOD: An authorization check is made. |
| 49 | + public async Task<IActionResult> Edit5(int commentId, string text) |
| 50 | + { |
| 51 | + var authResult = await _authorizationService.AuthorizeAsync(User, "Comment", "EditPolicy"); |
| 52 | + |
| 53 | + if (authResult.Succeeded) |
| 54 | + { |
| 55 | + editComment(commentId, text); |
| 56 | + return View(); |
| 57 | + } |
| 58 | + return Forbid(); |
| 59 | + } |
| 60 | + |
| 61 | + // GOOD: Only users with the `admin` role can access this method. |
| 62 | + [Authorize(Roles = "admin")] |
| 63 | + public async Task<IActionResult> Edit6(int commentId, string text) |
| 64 | + { |
30 | 65 | editComment(commentId, text); |
31 | 66 | return View(); |
32 | 67 | } |
|
0 commit comments