WeatherForecastController.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using JwtTest.Jwt;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.Extensions.Logging;
  9. namespace JwtTest.Controllers
  10. {
  11. [ApiController]
  12. [Route("[controller]")]
  13. public class WeatherForecastController : ControllerBase
  14. {
  15. private static readonly string[] Summaries = new[]
  16. {
  17. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
  18. };
  19. private readonly ILogger<WeatherForecastController> _logger;
  20. public WeatherForecastController(ILogger<WeatherForecastController> logger)
  21. {
  22. _logger = logger;
  23. }
  24. [HttpGet("Login")]
  25. public IActionResult Login(string role)
  26. {
  27. string jwtStr = string.Empty;
  28. bool suc = false;
  29. if (role != null)
  30. {
  31. // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。
  32. TokenModel tokenModel = new TokenModel { Uid = "abcde", Role = role };
  33. jwtStr = JwtHelper.IssueJwt(tokenModel);//登录,获取到一定规则的 Token 令牌
  34. suc = true;
  35. }
  36. else
  37. {
  38. jwtStr = "login fail!!!";
  39. }
  40. return Ok(new
  41. {
  42. success = suc,
  43. token = jwtStr
  44. });
  45. }
  46. [HttpGet]
  47. public IEnumerable<WeatherForecast> Get()
  48. {
  49. var rng = new Random();
  50. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
  51. {
  52. Date = DateTime.Now.AddDays(index),
  53. TemperatureC = rng.Next(-20, 55),
  54. Summary = Summaries[rng.Next(Summaries.Length)]
  55. })
  56. .ToArray();
  57. }
  58. /// <summary>
  59. /// 需要Admin权限
  60. /// </summary>
  61. /// <returns></returns>
  62. [HttpGet("Admin")]
  63. [Authorize(Roles = "Admin")]
  64. public IActionResult Admin()
  65. {
  66. return Ok("hello admin");
  67. }
  68. /// <summary>
  69. /// 需要System权限
  70. /// </summary>
  71. /// <returns></returns>
  72. [HttpGet("System")]
  73. [Authorize(Roles = "System")]
  74. public IActionResult System()
  75. {
  76. return Ok("hello System");
  77. }
  78. }
  79. }