使用Furion+sqlsugar,参考Furion官方文档中的开源案列Admin.NET,实现单用户登录
时间: 2024-02-09 08:10:11 浏览: 144
好的,以下是使用Furion+sqlsugar实现单用户登录的步骤:
1. 创建一个Furion项目,并添加sqlsugar和sqlsugar.extensions库的引用。
2. 在appsettings.json文件中添加数据库连接字符串配置,例如:
```
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=TestDb;Uid=root;Pwd=123456;"
}
}
```
3. 创建一个User表,用于存储用户信息,例如:
```
CREATE TABLE `User` (
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
`UserName` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
4. 在Startup.cs文件的ConfigureServices方法中添加sqlsugar的配置,例如:
```
services.AddSqlSugar(new ConnectionConfig()
{
ConnectionString = Configuration.GetConnectionString("DefaultConnection"),
DbType = DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
```
5. 在UserService.cs文件中定义一个用于验证用户登录的方法,例如:
```
public class UserService : IUserService
{
private readonly ISqlSugarClient _sqlSugarClient;
public UserService(ISqlSugarClient sqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
}
public async Task<bool> ValidateUserAsync(string userName, string password)
{
var user = await _sqlSugarClient.Queryable<User>().Where(u => u.UserName == userName && u.Password == password).FirstAsync();
return user != null;
}
}
```
6. 在AccountController.cs文件中定义一个用于处理用户登录的方法,例如:
```
public class AccountController : ApiControllerBase
{
private readonly IUserService _userService;
public AccountController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
public async Task<ActionResult> LoginAsync(LoginInputDto input)
{
if (await _userService.ValidateUserAsync(input.UserName, input.Password))
{
var identity = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.Name, input.UserName),
}, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return Ok(new { message = "登录成功!" });
}
else
{
return BadRequest("用户名或密码错误!");
}
}
[HttpGet]
public async Task<ActionResult> LogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(new { message = "退出登录成功!" });
}
}
```
7. 在Configure方法中添加Cookie身份验证中间件的配置,例如:
```
app.UseAuthentication();
app.UseAuthorization();
```
8. 在appsettings.json文件中添加身份验证配置,例如:
```
{
"Authentication": {
"Cookie": {
"LoginPath": "/Account/Login",
"LogoutPath": "/Account/Logout",
"AccessDeniedPath": "/Home/AccessDenied",
"Expiration": "1.00:00:00",
"SlidingExpiration": true
}
}
}
```
9. 编写前端页面,使用ajax请求登录接口,登录成功后跳转到主页面。
以上就是使用Furion+sqlsugar实现单用户登录的全部步骤,希望能对你有所帮助。
阅读全文