Chủ Nhật, 7 tháng 8, 2016

[ASP.NET MVC] Authentication và Authorize

[ASP.NET MVC] Authentication và Authorize

Một trong những vấn đề bảo mật cơ bản nhất là đảm bảo những người dùng hợp lệ truy cập vào hệ thống. ASP.NET đưa ra 2 khái niệm: Authentication và Authorize
Authentication xác nhận bạn là ai. Ví dụ: Bạn có thể đăng nhập vào hệ thống bằng username và password hoặc bằng ssh.
Authorization xác nhận những gì bạn có thể làm. Ví dụ: Bạn được phép truy cập vào website, đăng thông tin lên diễn đàn nhưng bạn không được phép truy cập vào trang mod và admin.

HẠN CHẾ TRUY CẬP VỚI AUTHORIZE ATTRIBUTE

ASP.NET MVC cung cấp filter AuthorizeAttribute, được thực hiện trước khi vào controller.
?
1
2
3
<authentication mode="Forms">
 <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Với form auuthentication được kích hoạt, nếu người dùng cố gắng truy cập vào một trang cần được xác thực, họ sẽ được chuyển hướng đến trang login (Account/Login) nhập tên người dùng và mật khẩu
Để yêu cầu xác thực 1 trang, bạn cần đặt AuthorizeAttribute trước Action cần kiểm tra:
?
1
2
3
4
5
[AuthorizeAttribute]
public ActionResult About()
{
    return View();
}
Hoặc bạn có thể ghi ngắn gọn hơn:
?
1
2
3
4
5
[Authorize]
public ActionResult About()
{
    return View();
}
Để lưu lại trang thái đăng nhập của người dùng, bạn dùng hàm FormsAuthentication.SetAuthCookie(username, rememberme)
Khi log out ra khỏi hệ thống, bạn dùng hàm FormsAuthentication.SignOut() để xóa cookie.
Đây là đoạn code hoàn chỉnh:
?
Account Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[Authorize]
public class AccountController : Controller
{
    private UserRepository _userRepository;
 
    public AccountController()
    {
        _userRepository = new UserRepository();
    }
    //
    // GET: /Account/Login
 
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }
 
    //
    // POST: /Account/Login
 
    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (_userRepository.Validate(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return RedirectToLocal(returnUrl);
        }
        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }
 
    //
    // POST: /Account/LogOff
 
    [HttpPost]
    public ActionResult LogOff()
    {
        //WebSecurity.Logout();
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }
 
    private ActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {
            return RedirectToAction("Index", "Home");
        }
    }       
}
?
User Repository
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class UserRepository
{
    private static List<User> _userList = new List<User>
    {
        new User{ Id = 1, Name = "admin", Password = "123"},
        new User{ Id = 2, Name = "anbinhtrong", Password = "123"}
    };
 
    public bool Validate(string username, string password)
    {
        var user = _userList.FirstOrDefault(t => t.Name == username);
        if (user == null)
            return false;
        if (user.Password == password) return true;
        return false;
    }
}
Chúc các bạn thành công.

Không có nhận xét nào:

Đăng nhận xét