CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Security trong Spring Web MVC với Hibernate và Oracle Database

Đăng lúc: 08:44 AM - 11/11/2023 bởi Charles Chung - 1726

Authentication và Authorization là hai quá trình rất quan trong trong việc bảo mật thông tin của các ứng dụng. Trong bài viết này mình sẽ hướng dẫn các bạn sử dụng tính năng Security trong Spring Web MVC để xác thực và phân quyền cho người dùng.

1. Cơ chế hoạt động của Security Spring

2. Mô tả yêu cầu

Tạo ứng dụng Spring Web MVC đáp ứng 2 vai trò là: Quản trị viên (ROLE_ADMIN), Sinh viên (ROLE_STUDENT), ứng với mỗi vai trò sẽ có giao diện riêng biệt, ROLE_ADMIN được vào mọi trang, ROLE_STUDENT chỉ vào trang dành cho sinh viên.

  • Thiết kế trang login cho người dùng, trang dành cho quản trị, trang dành cho sinh viên.
  • Thiết kế cơ sở dữ liệu đáp ứng yêu cầu trên, sử dụng Oracle để lưu trữ.
  • Truy xuất dữ liệu trong Oracle sử dụng Hibernate.
  • Sử dụng thư viện Security Spring để triển khai.

3. Chuẩn bị dữ liệu

  • Cấu trúc các bảng

  • Kịch bản tạo cơ sở dữ liệu (đính kèm theo source code)

4. Các bước thực hiện

Bước 1: Tạo Dynamic Web Project

  • Khởi động Eclispe IDE -> vào menu File -> New -> Dynamic Web Project -> Nhập tên project "SpringMVCSecurityHibernateOracle"
  • Tiếp tục kích vào Next -> Next -> Chọn Generate web.xml deyployment desciptor và kích Finish

Bước 2: Convert sang Maven Project

  • Kích chuột phải vào Project vừa tạo -> Configure -> Convert to Maven Project -> Finish

Bước 3: Khai báo các Maven Dependencies cần thiết trong file pom.xml

  • Mở file pom.xml và cấu hình các Maven Dependencies gồm: spring web, web mvc, orm, servlet api, jstl, hibernate core, security spring, oracle, jbcrypt

<dependencies>

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.5</version>

<scope>provided</scope>

</dependency>

<!--https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>5.3.18</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>5.3.18</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-orm</artifactId>

<version>5.3.18</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.4.26.Final</version>

</dependency>

<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc10 -->

<dependency>

<groupId>com.oracle.database.jdbc</groupId>

<artifactId>ojdbc10</artifactId>

<version>19.20.0.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-web</artifactId>

<version>5.8.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-config</artifactId>

<version>5.8.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.mindrot/jbcrypt -->

<dependency>

<groupId>org.mindrot</groupId>

<artifactId>jbcrypt</artifactId>

<version>0.4</version>

</dependency>

</dependencies>

 

Bước 5: Cấu hình ứng dụng Spring Web Mvc

  • Trong thư mục WEB-INF tạo thư mục views và tệp tin spring-servlet.xml cấu hình sau

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<!-- chỉ ra các package chứa các lớp java được đăng như các bean -->

<context:component-scan base-package="hanam88" />

<!-- chỉ tìm kiếm các bean trong cùng context application được định nghĩa -->

<context:annotation-config />

<!-- mặc định các basic components được ủy quyền gửi request tới các controller -->

<mvc:annotation-driven />

<!-- Cấu hình đường dẫn tài nguyên được phép truy cập -->

<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- Tạo bean xác định view sẽ được sinh ra (thư mục chứa các view, đuôi tệp tin view) -->

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp" />

<!-- Tạo đối tượng bean dataSource kết nối database oracle -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>

<property name="url" value="jdbc:oracle:thin:@localhost:1521:bkap"></property>

<property name="username" value="system"></property>

<property name="password" value="1234$"></property>

</bean>

<!-- Tạo đối tượng bean sessionFactory cấu hình Hibernate -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>

<property name="packagesToScan" value="hanam88.entities"></property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.current_session_context_class">thread</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>

</props>

</property>

</bean>

<!-- bean hóa mật khẩu với tham số strength 12 -->

<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">

<constructor-arg name="strength" value="12"></constructor-arg>

</bean>

</beans>

 

  • Trong thư mục WEB-INF tạo thư mục views và tệp tin spring-security.xml cấu hình sau

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans

xmlns="http://www.springframework.org/schema/security"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:beans="http://www.springframework.org/schema/beans"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

<http auto-config="true">

<csrf disabled="true"/>

<!-- cấu hình các vai trò truy cập -->

<intercept-url pattern="/resources/**" access="permitAll" />

<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />

<intercept-url pattern="/student/**" access="hasRole('ROLE_ADMIN') or hasRole('ROLE_STUDENT')" />

<!-- trang cấm truy cập -->

<access-denied-handler error-page="/403" />

<!-- cấu hình form login -->

<form-login login-page="/login"

login-processing-url="/loginProcess"

default-target-url="/checkrole"

authentication-failure-url="/login?error"

username-parameter="username"

password-parameter="password" />

<logout logout-url="/logout" logout-success-url="/logoutSuccess" delete-cookies="JSESSIONID" />

</http>

<!--

- cấu hình service xác định người dùng

- passwordEncoder đối tượng hóa mật khẩu,

- accountDetailsService đối tượng của lớp AccountDetailsService

-->

<authentication-manager>

<authentication-provider user-service-ref="accountDetailsService">

<password-encoder ref="passwordEncoder" />

</authentication-provider>

</authentication-manager>

</beans:beans>

 

  • Mở tệp web.xml và cấu hình vào bên trong thẻ <web-app> như sau:

<!-- add filter xử utf8 khi request response -->

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<listener>

<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/spring-servlet.xml,/WEB-INF/spring-security.xml</param-value>

</context-param>

<filter>

<filter-name>springSecurityFilterChain</filter-name>

<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

</filter>

<filter-mapping>

<filter-name>springSecurityFilterChain</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

 

Bước 6: Tạo các thư mục, package và tệp tin theo cấu trúc mô tả sau

 

 

  • Nội dung tệp login.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>

<head>

<title>ĐĂNG NHẬP</title>

<link rel="stylesheet"

href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container" style="margin-top:50px;">

<h3>ĐĂNG NHẬP HỆ THỐNG QUẢN LÝ ĐIỂM - BÁCH KHOA APTECH</h3>

<h4 style="color: red">${msg}</h4>

<form name='loginForm' action="<c:url value='loginProcess' />" method='POST'>

<table>

<tr>

<td>Tên đăng nhập</td>

<td><input type='text' name='username'></td>

</tr>

<tr>

<td>Mật khẩu</td>

<td><input type='password' name='password' /></td>

</tr>

<tr>

<td colspan='2'><input name="submit" type="submit" value="Đăng nhập" class="btn btn-primary" /></td>

</tr>

</table>

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

</form>

</div>

</body>

</html>

 

  • Nội dung tệp 403.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Thông báo quyền hạn</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<h1 style="color:red;margin-top:10px;">${msg}!</h1>

<a href="javascript:history.back()">Quay lại</a>

</div>

</body>

</html>

  • Nội dung tệp student/home.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<title>Chào bạn: ${account.fullName} </title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<p style="margin-top:10px;"><img src="${pageContext.servletContext.contextPath}/${account.avatar}" class="rounded-circle" width="40"/>

<b>${pageContext.request.userPrincipal.name}</b>

<a href="<c:url value='/logout'/>">Thoát</a>

</p>

<hr>

<h3>${msg}</h3>

<p>Chào bạn: ${account.fullName} </p>

</div>

</body>

</html>

 

  • Nội dung tệp admin/home.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>

<html>

<head>

<title>Chào bạn: ${account.fullName} </title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<p style="margin-top:10px;"><img src="${pageContext.servletContext.contextPath}/${account.avatar}" class="rounded-circle" width="40"/>

<b>${pageContext.request.userPrincipal.name}</b>

<a href="<c:url value='/logout'/>">Thoát</a>

</p>

<hr>

<h3>${msg}</h3>

<p>Chào bạn: ${account.fullName} </p>

</div>

</body>

</html>

 

  • Lớp hanam88.entities/Account.java

package hanam88.entities;

import java.util.Date;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

import org.springframework.format.annotation.DateTimeFormat;

@Entity

@Table(name="accounts")

public class Account {

@Id

@Column(name = "accountid")

private String accountid;

@Column(name = "username")

private String userName;

@Column(name = "password")

private String passWord;

@Column(name = "fullname")

private String fullName;

@Column(name = "gender")

private int gender;

@Column(name = "birthday")

@Temporal(value = TemporalType.DATE)

@DateTimeFormat(pattern = "dd/MM/yyyy")

private Date birthday;

@Column(name = "email")

private String email;

@Column(name = "phone")

private String phone;

@Column(name = "avatar")

private String avatar;

@Column(name = "note")

private String note;

@Column(name = "active")

private int active;

@OneToMany(mappedBy = "account", fetch = FetchType.EAGER)

private Set<AccountRole> accountroles;

public Account() {

// TODO Auto-generated constructor stub

}

public String getAccountid() {

return accountid;

}

public void setAccountid(String accountid) {

this.accountid = accountid;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassWord() {

return passWord;

}

public void setPassWord(String passWord) {

this.passWord = passWord;

}

public String getFullName() {

return fullName;

}

public void setFullName(String fullName) {

this.fullName = fullName;

}

public int getGender() {

return gender;

}

public void setGender(int gender) {

this.gender = gender;

}

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getAvatar() {

return avatar;

}

public void setAvatar(String avatar) {

this.avatar = avatar;

}

public String getNote() {

return note;

}

public void setNote(String note) {

this.note = note;

}

public int getActive() {

return active;

}

public void setActive(int active) {

this.active = active;

}

public Set<AccountRole> getAccountroles() {

return accountroles;

}

public void setAccountroles(Set<AccountRole> accountroles) {

this.accountroles = accountroles;

}

}

 

  • Lớp hanam88.entities/Role.java

package hanam88.entities;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

@Entity

@Table(name="roles")

public class Role {

@Id

@Column(name = "roleid")

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "rolename")

private String rolename;

@OneToMany(mappedBy = "role")

private Set<AccountRole> accountroles;

public Role() {

// TODO Auto-generated constructor stub

}

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getRolename() {

return rolename;

}

public void setRolename(String rolename) {

this.rolename = rolename;

}

public Set<AccountRole> getAccountroles() {

return accountroles;

}

public void setAccountroles(Set<AccountRole> accountroles) {

this.accountroles = accountroles;

}

}

 

  • Lớp hanam88.entities/AccountRole.java

package hanam88.entities;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

@Entity

@Table(name="accounts_roles")

public class AccountRole {

@Id

@Column(name = "id")

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@ManyToOne

@JoinColumn(name = "accountId")

private Account account;

@ManyToOne

@JoinColumn(name = "roleId")

private Role role;

public AccountRole() {

// TODO Auto-generated constructor stub

}

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public Account getAccount() {

return account;

}

public void setAccount(Account account) {

this.account = account;

}

public Role getRole() {

return role;

}

public void setRole(Role role) {

this.role = role;

}

}

 

  • Lớp hanam88.entities/AccountDetails.java

package hanam88.entities;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

//Lớp customzie userdetails để chứa đầy đủ thông tin người dùng

public class AccountDetails implements UserDetails {

private Collection<? extends GrantedAuthority> authorities;

private String email;

private String fullName;

private String password;

private String username;

private int gender;

private String avatar;

private String phone;

private boolean enabled;

private boolean accountNonExpired;

private boolean accountNonLocked;

private boolean credentialsNonExpired;

public AccountDetails() {

super();

// TODO Auto-generated constructor stub

}

public AccountDetails(Collection<? extends GrantedAuthority> authorities, String email, String fullName,

String password, String username, int gender, String avatar, String phone, int active,

boolean accountNonExpired, boolean accountNonLocked, boolean credentialsNonExpired) {

super();

this.authorities = authorities;

this.email = email;

this.fullName = fullName;

this.password = password;

this.username = username;

this.gender = gender;

this.avatar = avatar;

this.phone = phone;

this.enabled = active==0?false:true;

this.accountNonExpired = accountNonExpired;

this.accountNonLocked = accountNonLocked;

this.credentialsNonExpired = credentialsNonExpired;

}

public Collection<? extends GrantedAuthority> getAuthorities() {

return authorities;

}

public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {

this.authorities = authorities;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getFullName() {

return fullName;

}

public void setFullName(String fullName) {

this.fullName = fullName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public int getGender() {

return gender;

}

public void setGender(int gender) {

this.gender = gender;

}

public String getAvatar() {

return avatar;

}

public void setAvatar(String avatar) {

this.avatar = avatar;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public boolean isEnabled() {

return enabled;

}

public void setEnabled(boolean enabled) {

this.enabled = enabled;

}

public boolean isAccountNonExpired() {

return accountNonExpired;

}

public void setAccountNonExpired(boolean accountNonExpired) {

this.accountNonExpired = accountNonExpired;

}

public boolean isAccountNonLocked() {

return accountNonLocked;

}

public void setAccountNonLocked(boolean accountNonLocked) {

this.accountNonLocked = accountNonLocked;

}

public boolean isCredentialsNonExpired() {

return credentialsNonExpired;

}

public void setCredentialsNonExpired(boolean credentialsNonExpired) {

this.credentialsNonExpired = credentialsNonExpired;

}

}

 

  • Giao diện hanam88.dao/AccountDAO.java

package hanam88.dao;

import hanam88.entities.Account;

public interface AccountDAO {

public Account get(String username);

}

  • Lớp hanam88.dao/AccountImpl.java

package hanam88.dao;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import hanam88.entities.Account;

@Repository

public class AccountImpl implements AccountDAO {

@Autowired

private SessionFactory sessionFactory;

//lấy tài khoản người dùng trong db theo username

@Override

public Account get(String username) {

Session session = sessionFactory.openSession();

try {

Account account = (Account) session.createQuery("from Account where username = :username")

.setParameter("username", username).uniqueResult();

return account;

} catch (Exception e) {

e.printStackTrace();

} finally {

session.close();

}

return null;

}

}

 

  • Lớp hanam88.services/AccountDetailsService.java

package hanam88.services;

import java.util.Collection;

import java.util.HashSet;

import java.util.Set;

import hanam88.entities.Account;

import hanam88.entities.AccountDetails;

import hanam88.entities.AccountRole;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;

import hanam88.dao.AccountDAO;

@Service

public class AccountDetailsService implements UserDetailsService {

@Autowired

private AccountDAO accountDAO;

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

return getAccount(username);

}

//Lấy thông tin chi tiết của tài khoản người dùng theo username

private AccountDetails getAccount(String username) {

Account acc = accountDAO.get(username);

if (acc==null){

return null;

}

//xử lấy roles của người dùng đưa vào Authority

Collection<GrantedAuthority> grantedAuthoritySet = new HashSet<>();

Set<AccountRole> roles = acc.getAccountroles();

for (AccountRole accountRole : roles) {

String rolename=accountRole.getRole().getRolename();

grantedAuthoritySet.add(new SimpleGrantedAuthority(rolename));

}

return new AccountDetails(grantedAuthoritySet, acc.getEmail(), acc.getFullName(), acc.getPassWord(), acc.getUserName(), acc.getGender(), acc.getAvatar(), acc.getPhone(), acc.getActive(),true,true,true);

}

}

 

  • Lớp hanam88.controllers/HomeController.java

package hanam88.controllers;

import org.springframework.lang.Nullable;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import hanam88.entities.AccountDetails;

@Controller

public class HomeController {

@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)

public String login(@Nullable @RequestParam(value = "error") String error, Model model) {

if (error != null) {

model.addAttribute("msg", "Đăng nhập sai!");

}

return "login";

}

@RequestMapping(value = "/checkrole")

public String checkRole() {

//lấy thông tin tài khoản

AccountDetails account = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

//duyệt role để kiểm tra điều hướng

for(var g: account.getAuthorities()) {

if(g.getAuthority().equals("ROLE_ADMIN")) {

return "redirect:/admin/";

}

if(g.getAuthority().equals("ROLE_STUDENT")) {

return "redirect:/student/";

}

}

return "403";

}

@RequestMapping("/logoutSuccess")

public String logout(Model model) {

model.addAttribute("msg", "Logout thành công!!!");

return "login";

}

@RequestMapping("/403")

public String accessDenied(Model model) {

model.addAttribute("msg", "BẠN KHÔNG CÓ QUYỀN TRUY CẬP VÀO TRANG NÀY");

return "403";

}

}

 

  • Lớp hanam88.controllers/AdminController.java

package hanam88.controllers;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import hanam88.entities.AccountDetails;

@Controller

@RequestMapping("/admin")

public class AdminController {

@RequestMapping("/")

public String index(Model model) {

model.addAttribute("msg", "TRANG QUẢN LÝ ĐIỂM - DÀNH CHO QUẢN TRỊ");

//lấy thông tin tài khoản khi login thành công

AccountDetails account = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

model.addAttribute("account", account);

return "admin/home";

}

}

  • Lớp hanam88.controllers/StudentController.java

package hanam88.controllers;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import hanam88.entities.AccountDetails;

@Controller

@RequestMapping("/student")

public class StudentController {

@RequestMapping("/")

public String index(Model model) {

model.addAttribute("msg", "TRANG TRA CỨU ĐIỂM THI- DÀNH CHO SINH VIÊN");

//Lấy thông tin tài khoản khi login thành công

AccountDetails account = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

model.addAttribute("account", account);

return "student/home";

}

}

Kết quả

  • Màn hình đăng nhập

  • Màn hình admin

  • Màn hình student

  • Màn hình báo quyền hạn

Kích để tải source code bài Security trong Spring Web MVC với Hibernate và Oracle Database

Kích để tải source code bài Security trong Spring Web MVC với Hibernate và SQL Server Database

Training online liên hệ: Charles Chung

Video 

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ