123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using JwtTest.Jwt;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- namespace JwtTest.Controllers
- {
- [ApiController]
- [Route("[controller]")]
- public class WeatherForecastController : ControllerBase
- {
- private static readonly string[] Summaries = new[]
- {
- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
- };
- private readonly ILogger<WeatherForecastController> _logger;
- public WeatherForecastController(ILogger<WeatherForecastController> logger)
- {
- _logger = logger;
- }
- [HttpGet("Login")]
- public IActionResult Login(string role)
- {
- string jwtStr = string.Empty;
- bool suc = false;
- if (role != null)
- {
- // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。
- TokenModel tokenModel = new TokenModel { Uid = "abcde", Role = role };
- jwtStr = JwtHelper.IssueJwt(tokenModel);//登录,获取到一定规则的 Token 令牌
- suc = true;
- }
- else
- {
- jwtStr = "login fail!!!";
- }
- return Ok(new
- {
- success = suc,
- token = jwtStr
- });
- }
- [HttpGet]
- public IEnumerable<WeatherForecast> Get()
- {
- var rng = new Random();
- return Enumerable.Range(1, 5).Select(index => new WeatherForecast
- {
- Date = DateTime.Now.AddDays(index),
- TemperatureC = rng.Next(-20, 55),
- Summary = Summaries[rng.Next(Summaries.Length)]
- })
- .ToArray();
- }
- /// <summary>
- /// 需要Admin权限
- /// </summary>
- /// <returns></returns>
- [HttpGet("Admin")]
- [Authorize(Roles = "Admin")]
- public IActionResult Admin()
- {
- return Ok("hello admin");
- }
- /// <summary>
- /// 需要System权限
- /// </summary>
- /// <returns></returns>
- [HttpGet("System")]
- [Authorize(Roles = "System")]
- public IActionResult System()
- {
- return Ok("hello System");
- }
- }
- }
|