|
Проблема с Claims в ASP.NET Core MVC
#39510118
Ссылка:
Ссылка на сообщение:
Ссылка с названием темы:
|
|
|
|
Добрый день. Пишу небольшой проект на Core MVC и столкнулся с проблемой личного кабинета. Суть в том, что я использую 2 таблицы - Юзеры (основная) и результаты (дочерняя). Для авторизации и регистрации я использую Claims, и после авторизации юзер получает личную страницу, на которой выходят его данные. Но так же я пытаюсь сделать на этой странице таблицу с его результатами (а их несколько). Но у меня не получается эти строки в листы. Собственно, проблема с этих строках в методе Autentificate в классе AccountController
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.
private async Task Authenticate(User user)
{
Result currentResult = new Result();
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name),
new Claim("email", user.Email),
new Claim("login", user.Login),
new Claim("name", user.Name),
new Claim("surname", user.Surname),
new Claim("middlename", user.MiddleName),
new Claim("phone", user.Phone)
};
Result result = _context.Results.Where(x => x.UserId == user.UserId).FirstOrDefault();
claims.Add(new Claim("score", Convert.ToString(result.Score)));
claims.Add(new Claim("time", Convert.ToString(result.Time)));
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
//Thread.CurrentPrincipal = new ClaimsPrincipal(id);
await HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(id));
}
Подскажите пожалуйста, как эти строки
1. 2. 3.
Result result = _context.Results.Where(x => x.UserId == user.UserId).FirstOrDefault();
claims.Add(new Claim("score", Convert.ToString(result.Score)));
claims.Add(new Claim("time", Convert.ToString(result.Time)));
Сделать листами, чтобы выводилось несколько значений, а не только первое или последнее
Вот классы Юзер и результаты
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49.
using System;
using System.Collections.Generic;
using System.Text;
namespace GameWebService.DAL.Models
{
public class User
{
public Guid UserId { get; set; }
public int RoleId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string MiddleName { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public virtual ICollection<Result> Results { get; set; } = new List<Result>();
public Role Role { get; set; }
}
}
using System;
namespace GameWebService.DAL.Models
{
public class Result
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public int Score { get; set; }
public string Time { get; set; }
public User User { get; set; }
}
}
Вот AccountController
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using GameWebService.DAL.EntityFramework;
using GameWebService.DAL.Models;
using GameWebService.ViewModels;
using System;
using System.Linq;
using System.Threading;
using System.Security.Principal;
namespace GameWebService.Controllers
{
public class AccountController : Controller
{
private GameServiceContext _context;
public AccountController(GameServiceContext context)
{
_context = context;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegistrationViewModel model)
{
if (ModelState.IsValid)
{
User user = await _context.Users.FirstOrDefaultAsync(u => u.Email == model.Email);
if (user == null)
{
// добавляем пользователя в бд
user = new User {Surname = model.Surname, Name = model.Name, MiddleName = model.MiddleName, Login = model.Login, Phone = model.Phone, Email = model.Email, Password = model.Password };
Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "user");
if (userRole != null)
user.Role = userRole;
_context.Users.Add(user);
await _context.SaveChangesAsync();
await Authenticate(user); // аутентификация
return RedirectToAction("Results", "Home");
}
else
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return View(model);
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
User user = await _context.Users
.Include(u => u.Role)
.FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password);
if (user != null)
{
await Authenticate(user); // аутентификация
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return View(model);
}
private async Task Authenticate(User user)
{
Result currentResult = new Result();
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name),
new Claim("email", user.Email),
new Claim("login", user.Login),
new Claim("name", user.Name),
new Claim("surname", user.Surname),
new Claim("middlename", user.MiddleName),
new Claim("phone", user.Phone)
};
Result result = _context.Results.Where(x => x.UserId == user.UserId).FirstOrDefault();
claims.Add(new Claim("score", Convert.ToString(result.Score)));
claims.Add(new Claim("time", Convert.ToString(result.Time)));
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
//Thread.CurrentPrincipal = new ClaimsPrincipal(id);
await HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(id));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.Authentication.SignOutAsync("Cookies");
return RedirectToAction("Login", "Account");
}
}
}
Вот Home Controller
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93.
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using GameWebService.DAL.EntityFramework;
using System.Threading.Tasks;
using GameWebService.DAL.Models;
using GameWebService.ViewModels;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Security.Claims;
namespace GameWebService.Controllers
{
public class HomeController : Controller
{
GameServiceContext db;
public HomeController(GameServiceContext context)
{
db = context;
}
[Authorize(Roles = "admin, user")]
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
public IActionResult Results()
{
return View(db.Results.ToList());
}
public IActionResult Cabinet()
{
return View();
}
public IActionResult Users()
{
return View(db.Users.ToList());
}
[HttpGet]
public IActionResult CreateUser()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateUser(RegistrationViewModel model)
{
if (ModelState.IsValid)
{
User user = await db.Users.FirstOrDefaultAsync(u => u.Email == model.Email);
if (user == null)
{
// добавляем пользователя в бд
user = new User { Surname = model.Surname, Name = model.Name, MiddleName = model.MiddleName, Login = model.Login, Phone = model.Phone, Email = model.Email, Password = model.Password };
Role userRole = await db.Roles.FirstOrDefaultAsync(r => r.Name == "user");
if (userRole != null)
user.Role = userRole;
db.Users.Add(user);
await db.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
else
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return View(model);
}
}
}
Вот выходная страница
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.
@model IEnumerable<GameWebService.DAL.Models.Result>
@using System.Security.Claims
@using GameWebService.DAL.Models
<div>Email: @User.FindFirst(x => x.Type == "email").Value</div>
<div>Логин: @User.FindFirst(x => x.Type == "login").Value</div>
<div>Фамилия: @User.FindFirst(x => x.Type == "surname").Value</div>
<div>Имя: @User.FindFirst(x => x.Type == "name").Value</div>
<div>Отчество: @User.FindFirst(x => x.Type == "middlename").Value</div>
<div>Номер телефона: @User.FindFirst(x => x.Type == "phone").Value</div>
<div>Последние результаты: </div>
<html>
<body>
<table>
<tr>
<td></td>
<td>Очки</td>
<td>Время</td>
<td></td>
</tr>
@*@foreach (var claim in User.FindFirst(x => x.Type == "result").Value.ToList())
{*@
<tr>
<td>@User.FindFirst(x => x.Type == "score").Value</td>
<td>@User.FindFirst(x => x.Type == "time").Value</td>
</tr>
@*}*@
</table>
</body>
</html>
Помогите пожалуйста разобраться с этой проблемой!
|
|
|