所以我有一个使用JWT创建,登录等的api。现在,我的Login类太广泛了,对我的爱好负有太多责任。在这里;
[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto user)
{
var userFromRepo = await _qrepo.Login(user.Username, user.Password);
//IF no user found in db
if (userFromRepo == null)
//Return unauth so if user have wrong login creds, we're not specifying if it's password or username
return Unauthorized();
//Token creation
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Username)
};
// Hashed token Key
// The token is unique and very secret - if you have the token you are able to create tokens that are verifyable for our backend
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
// Signing credentials
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
// Security Token DEscripter
var tokenDescriptor = new SecurityTokenDescriptor
{
// our claims
Subject = new ClaimsIdentity(claims),
// Expiry date - 1 day from create
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
// Token handler
var tokenHandler = new JwtSecurityTokenHandler();
// Actual token
var token = tokenHandler.CreateToken(tokenDescriptor);
// Return actual token
return Ok(new
{
token = tokenHandler.WriteToken(token)
});
}
我希望将令牌创建与我的Controller方法分开,但是我不确定是否最好的方法是什么,那么这将属于什么?这是我的文件夹结构:
我不觉得它属于我的两个文件夹,但也许属于助手,idk?什么是标准方法?
答案 0 :(得分:1)
您可以将所有令牌生成内容放到单独的服务类中吗? 然后使用DI注入服务。 还给它一个界面,以便您可以更轻松地对其进行测试:
public interface IJwtTokenGenerator
{
string GenerateToken(User user);
}
public class JwtTokenGenerator : IJwtTokenGenerator
{
private readonly IConfiguration _config;
public JwtTokenGenerator(IConfiguration config)
{
_config = config;
}
//obviously, change User to whatever your user class name is
public string GenerateToken(User user)
{
//Token creation
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username)
};
// Hashed token Key
// The token is unique and very secret - if you have the token you are able to create tokens that are verifyable for our backend
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
// Signing credentials
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
// Security Token DEscripter
var tokenDescriptor = new SecurityTokenDescriptor
{
// our claims
Subject = new ClaimsIdentity(claims),
// Expiry date - 1 day from create
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
// Token handler
var tokenHandler = new JwtSecurityTokenHandler();
// Actual token
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(securityToken);
}
}
然后您的登录操作可能类似于:
[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto user)
{
var userFromRepo = await _qrepo.Login(user.Username, user.Password);
//IF no user found in db
if (userFromRepo == null)
//Return unauth so if user have wrong login creds, we're not specifying if it's password or username
return Unauthorized();
//Injected ITokenGenerator (note the interface)
var token = _tokenGenerator.GenerateToken(userFromRepo);
// Return actual token
return Ok(new
{
token
});
}
关于放置此类和接口的文件夹(应该是两个单独的文件),它主要取决于对您或您的团队有意义的内容。也许是另一个名为“服务”的文件夹,也许是“身份验证”,也许是“身份验证/服务”。 “助手”通常用于静态类,但我想可以将其放在那里。