如何确保我的页面安全,只有经过身份验证的人才能访问这些页面



我在web应用程序上设置了一个身份验证表单,但我仍然可以访问所有其他页面。在通过身份验证之前,我如何阻止自己访问这些页面?

我创建了一个接口,这样我就可以使用Login方法,该方法将接受用户名和密码,如果绑定成功,则返回true或false。

接口

using System;
using HSLogApp.Classes;
namespace HSLogApp.Interfaces
{
public interface IAuthService
{
bool Login(string username, string password);
}
}

我创建了一个继承接口的类。连接是在构造函数中进行的,Login方法用于接收用户名和密码。

身份验证类

using System;
using System.Linq;
using HSLogApp.Interfaces;
using Microsoft.Extensions.Options;
using Novell.Directory.Ldap;
namespace HSLogApp.Classes
{
class LdapAuthenticationService : IAuthService
{
private const string MemberOfAttribute = "memberOf";
private const string DisplayNameAttribute = "displayName";
private const string SAMAccountNameAttribute = "sAMAccountName";
private readonly LdapConfig _config;
private readonly LdapConnection connection;
public LdapAuthenticationService(IOptions<LdapConfig> config)
{
_config = config.Value;
connection = new LdapConnection
{
SecureSocketLayer = true
};
try
{
connection.Connect(_config.Url, _config.Port);
// _connection.Bind(username, password);
}
catch (LdapException lex)
{
Console.WriteLine("CONNECTION ERROR");
Console.WriteLine("DETAILS - " + lex.ToString());
}
}
public bool Login(string Username, string Password)
{
try
{
connection.Bind(Username, Password);
}
catch
{
return false;
}
return true;
}
}
}

编辑视图:

@page
@model IndexModel
@{
ViewData["Title"] = "Login";
}
<div class="box-header">
<h2>Log In</h2>
</div>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<label for="username">Username</label>
<br />
<input type="email" id="Username" asp-for="Username" class="form-control">
<br />
<label for="password">Password</label>
<br />
<input type="password" id="Password" asp-for="Password" class="form-control">
<br />
<button type="submit">Sign In</button>
<br />
</form>
<a href="#"><p class="small">Forgot your password?</p></a>
<br>
@if(User.Identity.IsAuthenticated)
{
<p class="alert alert-success">
You are successfully authenticated.
</p>
}

查看代码隐藏显示如何检查身份验证。

public async Task<ActionResult> OnPostAsync(string returnUrl = null)
{
bool user = _authService.Login(Username, Password);
if (user)
{
Result = true;
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, Username)
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties { IsPersistent = true };
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return RedirectToPage("/hslogs/index");
}
else
{
Result = false;
return RedirectToPage();
}
}

我希望这就是你所需要的。如果我需要发布更多的代码/信息来让你了解我的情况,请告诉我。

我在public class IndexModel: PageModel正上方的命名空间下方的控制器顶部添加了[Authorize]

它看起来像这样:

[Authorize]
public class IndexModel: PageModel
{
...
{

相关内容

最新更新