44using System . IdentityModel . Tokens . Jwt ;
55using System . Linq ;
66using System . Security . Claims ;
7+ using System . Text ;
78using System . Threading . Tasks ;
89using Microsoft . AspNetCore . Http ;
910using Microsoft . AspNetCore . Mvc ;
@@ -16,29 +17,37 @@ namespace APIJSON.NET.Controllers
1617 [ ApiController ]
1718 public class TokenController : ControllerBase
1819 {
19- private DbOptions _options ;
20+ private DbContext db ;
2021 private readonly IOptions < TokenAuthConfiguration > _configuration ;
21- public TokenController ( IOptions < DbOptions > options , IOptions < TokenAuthConfiguration > configuration )
22+ public TokenController ( DbContext _db , IOptions < TokenAuthConfiguration > configuration )
2223 {
23- this . _options = options . Value ;
2424 _configuration = configuration ;
25+ db = _db ;
2526 }
26- [ HttpPost ( "/token" ) ]
27- public IActionResult Create ( string username , string password )
27+ [ HttpGet ( "/token" ) ]
28+ public IActionResult Create ( TokenInput input )
2829 {
2930 JObject ht = new JObject ( ) ;
3031 ht . Add ( "code" , "200" ) ;
3132 ht . Add ( "msg" , "success" ) ;
32- if ( username != password )
33+ var us = db . LoginDb . GetSingle ( it => it . userName == input . username ) ;
34+ if ( us == null )
3335 {
34-
36+ ht [ "code" ] = "201" ;
37+ ht [ "msg" ] = "用户名或者密码错误!" ;
38+ return Ok ( ht ) ;
39+ }
40+ string str = SimpleStringCipher . Instance . Encrypt ( input . password , null , Encoding . ASCII . GetBytes ( us . passWordSalt ) ) ;
41+ if ( ! us . passWord . Equals ( str ) )
42+ {
43+ ht [ "code" ] = "201" ;
44+ ht [ "msg" ] = "用户名或者密码错误!" ;
45+ return Ok ( ht ) ;
3546 }
36-
3747 var identity = new ClaimsIdentity ( ) ;
38- identity . AddClaim ( new Claim ( ClaimTypes . NameIdentifier , "1" ) ) ;
39- identity . AddClaim ( new Claim ( ClaimTypes . Name , "1" ) ) ;
40- identity . AddClaim ( new Claim ( ClaimTypes . Role , "" ) ) ;
41- identity . AddClaim ( new Claim ( JwtRegisteredClaimNames . Sub , username ) ) ;
48+ identity . AddClaim ( new Claim ( ClaimTypes . NameIdentifier , us . userId . ToString ( ) ) ) ;
49+ identity . AddClaim ( new Claim ( ClaimTypes . Role , us . roleCode ) ) ;
50+ identity . AddClaim ( new Claim ( JwtRegisteredClaimNames . Sub , input . username ) ) ;
4251 identity . AddClaim ( new Claim ( JwtRegisteredClaimNames . Jti , Guid . NewGuid ( ) . ToString ( ) ) ) ;
4352 identity . AddClaim ( new Claim ( JwtRegisteredClaimNames . Iat , DateTimeOffset . Now . ToUnixTimeSeconds ( ) . ToString ( ) , ClaimValueTypes . Integer64 ) ) ;
4453
@@ -69,6 +78,11 @@ private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration
6978 return new JwtSecurityTokenHandler ( ) . WriteToken ( jwtSecurityToken ) ;
7079 }
7180 }
81+ public class TokenInput
82+ {
83+ public string username { get ; set ; }
84+ public string password { get ; set ; }
85+ }
7286 public class AuthenticateResultModel
7387 {
7488 public string AccessToken { get ; set ; }
0 commit comments