日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

Spring MVC:MySQL和Hibernate的安全性

發布時間:2023/12/3 数据库 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring MVC:MySQL和Hibernate的安全性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Spring有很多不同的模塊。 所有這些對于具體目的都是有用的。 今天,我將討論Spring Security。 該模塊提供了靈活的方法來管理訪問Web應用程序不同部分的許可。 在這篇文章中,我將研究Spring MVCHibernateMySQLSpring Security的集成。

任何Web應用程序的常規情況都是某些用戶組之間的功能分離。 例如,具有“主持人”角色的用戶可以編輯數據庫中的現有記錄。 一個用戶
具有“管理員”角色的用戶可以執行與具有“主持人”角色的用戶相同的操作,并創建新記錄。 在Spring MVC中,可以使用Spring Security來實現許可管理。

目標

作為示例,我將在Hibernate中使用示例Spring MVC應用程序。 用戶及其角色將存儲在數據庫中。 MySQL將用作數據庫。 我將創建三個表:用戶,角色,user_roles。 您可能會猜到user_roles表是一個中間表 。 在應用程序中將扮演兩個角色:主持人和管理員。 將有幾個頁面可供主持人和管理員訪問。

制備

為了使Spring Security在項目中可用,只需在pom.xml文件中添加以下依賴項:

<!-- Spring Security --><dependency><groupid>org.springframework.security</groupid><artifactid>spring-security-core</artifactid><version>3.1.3.RELEASE</version></dependency><dependency><groupid>org.springframework.security</groupid><artifactid>spring-security-web</artifactid><version>3.1.3.RELEASE</version></dependency><dependency><groupid>org.springframework.security</groupid><artifactid>spring-security-config</artifactid><version>3.1.3.RELEASE</version></dependency>

我必須在數據庫中創建三個表,并在其中插入幾條記錄。

CREATE TABLE `roles` (`id` int(6) NOT NULL AUTO_INCREMENT,`role` varchar(20) NOT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;CREATE TABLE `users` (`id` int(6) NOT NULL AUTO_INCREMENT,`login` varchar(20) NOT NULL,`password` varchar(20) NOT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;CREATE TABLE `user_roles` (`user_id` int(6) NOT NULL,`role_id` int(6) NOT NULL,KEY `user` (`user_id`),KEY `role` (`role_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

這是角色和用戶的代碼:

INSERT INTO hibnatedb.roles (role) VALUES ('admin'), ('moderator');INSERT INTO hibnatedb.users (login, password) VALUES ('moder', '111111'), ('adm', '222222');INSERT INTO hibnatedb.user_roles (user_id, role_id) VALUES (1, 2), (2, 1);

主要部分

項目的完整結構具有以下結構:

由于您可以在GitHub上找到該項目,因此我將忽略當前主題之外的一些內容。 我想從每個Web項目的心臟開始,我的意思是web.xml文件。 Spring Security基于簡單的過濾器,因此我需要在部署描述符中添加過濾器的聲明:

...<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> ...

現在是時候為用戶和角色表創建實體了:

@Entity @Table(name="users") public class User {@Id@GeneratedValueprivate Integer id;private String login;private String password;@OneToOne(cascade=CascadeType.ALL)@JoinTable(name="user_roles",joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")})private Role role;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLogin() {return login;}public void setLogin(String login) {this.login = login;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Role getRole() {return role;}public void setRole(Role role) {this.role = role;} }

@Entity @Table(name="roles") public class Role {@Id@GeneratedValueprivate Integer id;private String role;@OneToMany(cascade=CascadeType.ALL)@JoinTable(name="user_roles", joinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")},inverseJoinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")})private Set userRoles;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getRole() {return role;}public void setRole(String role) {this.role = role;}public Set getUserRoles() {return userRoles;}public void setUserRoles(Set userRoles) {this.userRoles = userRoles;}}

每個實體類都需要DAO和Service層。

public interface UserDAO {public User getUser(String login);}

@Repository public class UserDAOImpl implements UserDAO {@Autowiredprivate SessionFactory sessionFactory;private Session openSession() {return sessionFactory.getCurrentSession();}public User getUser(String login) {List userList = new ArrayList();Query query = openSession().createQuery("from User u where u.login = :login");query.setParameter("login", login);userList = query.list();if (userList.size() > 0)return userList.get(0);elsereturn null; }}

分別用于Role類:

public interface RoleDAO {public Role getRole(int id);}

@Repository public class RoleDAOImpl implements RoleDAO {@Autowiredprivate SessionFactory sessionFactory;private Session getCurrentSession() {return sessionFactory.getCurrentSession();}public Role getRole(int id) {Role role = (Role) getCurrentSession().load(Role.class, id);return role;}}

服務層使用相同的對:

public interface UserService {public User getUser(String login);}

@Service @Transactional public class UserServiceImpl implements UserService {@Autowiredprivate UserDAO userDAO;public User getUser(String login) {return userDAO.getUser(login);}}

分別用于Role類:

public interface RoleService {public Role getRole(int id);}

@Service @Transactional public class RoleServiceImpl implements RoleService {@Autowiredprivate RoleDAO roleDAO;public Role getRole(int id) {return roleDAO.getRole(id);}}

以上只是機械的常規代碼。 現在讓我們研究Spring Security代碼。 為了將Spring Security插入到項目中,我必須創建CustomUserDetailsS??ervice類并實現UserDetailsS??ervice接口。

import java.util.ArrayList; import java.util.Collection; import java.util.List;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.User; 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 org.springframework.transaction.annotation.Transactional;import com.sprsec.dao.UserDAO;@Service @Transactional(readOnly=true) public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate UserDAO userDAO; public UserDetails loadUserByUsername(String login)throws UsernameNotFoundException {com.sprsec.model.User domainUser = userDAO.getUser(login);boolean enabled = true;boolean accountNonExpired = true;boolean credentialsNonExpired = true;boolean accountNonLocked = true;return new User(domainUser.getLogin(), domainUser.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,getAuthorities(domainUser.getRole().getId()));}public Collection getAuthorities(Integer role) {List authList = getGrantedAuthorities(getRoles(role));return authList;}public List getRoles(Integer role) {List roles = new ArrayList();if (role.intValue() == 1) {roles.add("ROLE_MODERATOR");roles.add("ROLE_ADMIN");} else if (role.intValue() == 2) {roles.add("ROLE_MODERATOR");}return roles;}public static List getGrantedAuthorities(List roles) {List authorities = new ArrayList();for (String role : roles) {authorities.add(new SimpleGrantedAuthority(role));}return authorities;}}

該類的主要目的是將應用程序的User類映射到Spring Security的User類。 這是Spring Security的殺手級功能之一。 這樣,您可以使任何種類的Spring MVC應用程序適應Security模塊的使用。

控制器和視圖

有關Spring Security的最常見問題之一是如何創建自定義登錄表單 。 答案很簡單。 您需要使用該表單創建一個JSP文件,并在其中指定action屬性()。

URL映射的大部分取決于spring-security.xml文件:

...<http auto-config="true"><intercept-url pattern="/sec/moderation.html" access="ROLE_MODERATOR"><intercept-url pattern="/admin/*" access="ROLE_ADMIN"><form-login login-page="/user-login.html" default-target-url="/success-login.html" authentication-failure-url="/error-login.html"><logout logout-success-url="/index.html"></logout></form-login></intercept-url></intercept-url></http><authentication-manager><authentication-provider user-service-ref="customUserDetailsService"><password-encoder hash="plaintext"></password-encoder></authentication-provider></authentication-manager> ...

如您所見,我為以下各項指定了URL:登錄頁面,成功登錄后的默認頁面,憑據無效情況下的錯誤頁面。 我也聲明了需要一些訪問許可的URL。 最重要的是身份驗證管理器的聲明。 通過這種方式,Spring Security將使用數據庫來識別用戶及其角色。

控制器:

@Controller public class LinkNavigation {@RequestMapping(value="/", method=RequestMethod.GET)public ModelAndView homePage() {return new ModelAndView("home");}@RequestMapping(value="/index", method=RequestMethod.GET)public ModelAndView indexPage() {return new ModelAndView("home");}@RequestMapping(value="/sec/moderation", method=RequestMethod.GET)public ModelAndView moderatorPage() {return new ModelAndView("moderation");}@RequestMapping(value="/admin/first", method=RequestMethod.GET)public ModelAndView firstAdminPage() {return new ModelAndView("admin-first");}@RequestMapping(value="/admin/second", method=RequestMethod.GET)public ModelAndView secondAdminPage() {return new ModelAndView("admin-second");}}

@Controller public class SecurityNavigation {@RequestMapping(value="/user-login", method=RequestMethod.GET)public ModelAndView loginForm() {return new ModelAndView("login-form");}@RequestMapping(value="/error-login", method=RequestMethod.GET)public ModelAndView invalidLogin() {ModelAndView modelAndView = new ModelAndView("login-form");modelAndView.addObject("error", true);return modelAndView;}@RequestMapping(value="/success-login", method=RequestMethod.GET)public ModelAndView successLogin() {return new ModelAndView("success-login");}}

您可以在GitHub上看到的視圖 。

請注意在WebAppConfig java類中添加@ImportResource(“ classpath:spring-security.xml”)。

摘要

我認為本文將幫助您深入了解Spring Security。 我在這里使用了Hibernate和MySQL,因為這樣的技術組合在Internet上的其他教程中并不經常使用。 可能您注意到我在項目中使用了一些XML,這是因為當前尚無辦法使用基于注釋的方法來實現所有這些東西。

參考資料: Spring MVC:來自JCG合作伙伴 Alexey Zvolinskiy(來自Fruzenshtein的注釋博客)的MySQL和Hibernate的安全性 。

翻譯自: https://www.javacodegeeks.com/2013/05/spring-mvc-security-with-mysql-and-hibernate.html

總結

以上是生活随笔為你收集整理的Spring MVC:MySQL和Hibernate的安全性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。