(1)Spring-Security对Web安全性的支持大量地依赖于Servlet过滤器。
(2)如果使用过Servlet过滤器且令其正常工作,就必须在Web应用程序的web.xml文件中使用
和
元素配置它们。虽然这样做能起作用,但是它并不适用于使用依赖注入进行的配置。
(3)spring-Security过滤器在进入服务器Tomcat之后,进入Servlet之前生效
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-webartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-configartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-coreartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-taglibsartifactId>
<version>${spring.security.version}version>
dependency>
<filter>
<filter-name>springSecurityFilterChainfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSecurityFilterChainfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"></security:global-method-security>
<!-- 配置不拦截的资源 -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/failer.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>
<!--
配置具体的规则
auto-config="true" 不用自己编写登录的页面,框架提供默认登录页面
use-expressions="false" 是否使用SPEL表达式(没学习过)
-->
<security:http auto-config="true" use-expressions="true">
<!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,ROLE_USER必须有的角色" -->
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
<security:form-login login-page="/login.jsp"
login-processing-url="/login.do"
default-target-url="/index.jsp"
authentication-failure-url="/failer.jsp"
authentication-success-forward-url="/pages/main.jsp"/>
<!-- 关闭跨域请求 -->
<security:csrf disabled="true"/>
<!--退出并跳转到首页-->
<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp"></security:logout>
</security:http>
<!-- 切换成数据库中的用户名和密码 -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<!-- 配置加密的方式
<security:password-encoder ref="passwordEncoder"/> -->
</security:authentication-provider>
</security:authentication-manager>
<!-- 配置加密类 -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<!-- <bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />-->
<!-- 提供了入门的方式,在内存中存入用户名和密码
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
-->
</beans>
(1)UserInfo
package com.zjitc.bean;
import java.util.List;
public class UserInfo {
private int id; //用户ID
private String username; //用户名
private String password; //用户密码
private List<Role> roleList;
// get/set 访问器
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
(2)Role
package com.zjitc.bean;
public class Role {
private int rid;
private String rname;
private String rdesc;
private String sex;
private String birthday;
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public String getRdesc() {
return rdesc;
}
public void setRdesc(String rdesc) {
this.rdesc = rdesc;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public Role() {
}
public Role(int rid, String rname, String rdesc, String sex, String birthday) {
this.rid = rid;
this.rname = rname;
this.rdesc = rdesc;
this.sex = sex;
this.birthday = birthday;
}
@Override
public String toString() {
return "Role{" +
"rid=" + rid +
", rname='" + rname + '\'' +
", rdesc='" + rdesc + '\'' +
", sex='" + sex + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
}
(1)IUserInfoDao
package com.zjitc.dao;
import com.zjitc.bean.UserInfo;
import java.util.List;
// IUserInfoDao - 接口,数据库访问层,直接可以访问数据库
public interface IUserInfoDao {
// 查询全部用户
List<UserInfo> findAll(Integer page,Integer size);
}
(2)IRoleDao
package com.zjitc.dao;
import com.zjitc.bean.Role;
import java.util.List;
public interface IRoleDao {
// 查询全部角色
List<Role> findAllRole(Integer page , Integer size);
// 通过用户ID查找该用户下的角色
List<Role> findRoleByUserId(int uid);
}
(1)UserInfoMapper.xml
<mapper namespace="com.zjitc.dao.IUserInfoDao">
<select id="findAll" resultType="com.zjitc.bean.UserInfo">
select * from tb_user
select>
mapper>
(2)RoleMapper.xml
<mapper namespace="com.zjitc.dao.IRoleDao">
<select id="findAllRole" resultType="com.zjitc.bean.Role">
select * from tb_role
select>
<select id="findRoleByUserId" parameterType="Integer" resultType="com.zjitc.bean.Role">
select * from tb_role where rid in(select rid from tb_user_role where uid=#{uid})
select>
mapper>
(1)
package com.zjitc.service;
import com.zjitc.bean.UserInfo;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.List;
public interface IUserInfoService extends UserDetailsService {
List<UserInfo> findAll(Integer page,Integer size);
}
package com.zjitc.service.impl;
import com.github.pagehelper.PageHelper;
import com.zjitc.bean.Role;
import com.zjitc.bean.UserInfo;
import com.zjitc.dao.IRoleDao;
import com.zjitc.dao.IUserInfoDao;
import com.zjitc.service.IUserInfoService;
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.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Service("userService")
public class UserInfoServiceImpl implements IUserInfoService {
@Autowired
private IUserInfoDao userInfoDao;
@Autowired
private IRoleDao roleDao;
@Override
public List<UserInfo> findAll(Integer page,Integer size) {
PageHelper.startPage(page,size);
return userInfoDao.findAll(page,size);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 根据姓名查询当前登录的用户
UserInfo userInfo = userInfoDao.doLogin(username);
// 根据当前登录的用户ID,去查询到所属的角色
List<Role> roleList = roleDao.findRoleByUserId(userInfo.getId());
userInfo.setRoleList(roleList);
// 得到想要的信息之后,就要交给Security去处理了
User user = new User(userInfo.getUsername(),"{noop}" + userInfo.getPassword(),getAuthority(roleList));
return user;
}
private Collection<? extends GrantedAuthority> getAuthority(List<Role> roleList) {
List<SimpleGrantedAuthority> list = new ArrayList<>();
for (Role role:roleList){
list.add(new SimpleGrantedAuthority("ROLE_" + role.getRname()));
}
return list;
}
}
(2)
package com.zjitc.service;
import com.zjitc.bean.Role;
import java.util.List;
public interface IRoleService {
List<Role> findAllRole(Integer page , Integer size);
}
package com.zjitc.service.impl;
import com.github.pagehelper.PageHelper;
import com.zjitc.bean.Role;
import com.zjitc.dao.IRoleDao;
import com.zjitc.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RoleServiceImpl implements IRoleService {
@Autowired
private IRoleDao roleDao;
@Override
public List<Role> findAllRole(Integer page , Integer size) {
PageHelper.startPage(page,size);
return roleDao.findAllRole(page,size);
}
}
(1)UserInfoController
package com.zjitc.controller;
import com.github.pagehelper.PageInfo;
import com.zjitc.bean.UserInfo;
import com.zjitc.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserInfoController {
@Autowired
private IUserInfoService userInfoService;
// 全部查询
// 所有需要返回数据到页面显示的全部都需要封装到ModelAndView中
@RequestMapping("/findAll.do")
public ModelAndView findAll(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "5") Integer size){
List<UserInfo> userInfoList = userInfoService.findAll(page,size);
PageInfo pageInfo = new PageInfo(userInfoList);
ModelAndView mv = new ModelAndView();
mv.addObject("pageInfo",pageInfo);
mv.setViewName("user-list");
return mv;
}
}
(2)RoleController
package com.zjitc.controller;
import com.github.pagehelper.PageInfo;
import com.zjitc.bean.Role;
import com.zjitc.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired private IRoleService roleService;
@RequestMapping("/findAllRole.do")
public ModelAndView findAll(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "5") Integer size){
List<Role> roleList = roleService.findAllRole(page,size);
// 创建出分页的内置对象,将查询到的List数据传到对象中
PageInfo pageInfo = new PageInfo(roleList);
ModelAndView mv = new ModelAndView();
mv.addObject("pageInfo",pageInfo);
mv.setViewName("role-list");
return mv;
}
}
<%-- access="hasRole('显示该链接必须要有的角色')" --%>
<security:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/user/findAll.dopage=1&size=5">
<i class="fa fa-circle-o">i> 用户管理
a>
security:authorize>