using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace JwtAuth.Controllers
{
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
//添加dll的引用 Nuget Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IdentityModel.Tokens.Jwt;
[Route("api/[controller]")]
public class AuthController : Controller
{
public JwtSettings settings;
public AuthController(IOptions<JwtSettings> jwtsettings)
{
settings = jwtsettings.Value;
}
[HttpPost]
public IActionResult Token([FromBody]LoginInfo model)
{
if (ModelState.IsValid)
{
if (model.username == "cyao" && model.password == "")
{
//用户合法情况
//添加授权信息
var claims = new Claim[] { new Claim(ClaimTypes.Name, "cyao"), new Claim(ClaimTypes.Role, "admin") };
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
settings.Issuer,
settings.Audience,
claims,
DateTime.Now,
DateTime.Now.AddMinutes(),//过期时间
creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
}
return BadRequest();
}
}
public class LoginInfo
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}
}