Spring Security和Shiro的比较和使用
https://blog.csdn.net/it_java_shuai/article/details/78054951
Spring Security和Shiro的比较和使用
这个文章是我找了几个博客总结到一块成为这个文章。
首先,先说比较吧!
这个博客地址是:http://www.cnblogs.com/aoeiuv/p/5868128.html
Shiro
首先Shiro较之 Spring Security,Shiro在保持强大功能的同时,还在简单性和灵活性方面拥有巨大优势。
Shiro是一个强大而灵活的开源安全框架,能够非常清晰的处理认证、授权、管理会话以及密码加密。如下是它所具有的特点:
- 易于理解的 Java Security API;
- 简单的身份认证(登录),支持多种数据源(LDAP,JDBC,Kerberos,ActiveDirectory 等);
- 对角色的简单的签权(访问控制),支持细粒度的签权;
- 支持一级缓存,以提升应用程序的性能;
- 内置的基于 POJO 企业会话管理,适用于 Web 以及非 Web 的环境;
- 异构客户端会话访问;
- 非常简单的加密 API;
- 不跟任何的框架或者容器捆绑,可以独立运行。
Spring Security
除了不能脱离Spring,shiro的功能它都有。而且Spring Security对Oauth、OpenID也有支持,Shiro则需要自己手动实现。Spring Security的权限细粒度更高(笔者还未发现高在哪里)。
注:
OAuth在"客户端"与"服务提供商"之间,设置了一个授权层(authorization layer)。"客户端"不能直接登录"服务提供商",只能登录授权层,以此将用户与客户端区分开来。"客户端"登录授权层所用的令牌(token),与用户的密码不同。用户可以在登录的时候,指定授权层令牌的权限范围和有效期。
"客户端"登录授权层以后,"服务提供商"根据令牌的权限范围和有效期,向"客户端"开放用户储存的资料。
OpenID 系统的第一部分是身份验证,即如何通过 URI 来认证用户身份。目前的网站都是依靠用户名和密码来登录认证,这就意味着大家在每个网站都需要注册用户名和密码,即便你使用的是同样的密码。如果使用 OpenID ,你的网站地址(URI)就是你的用户名,而你的密码安全的存储在一个 OpenID 服务网站上(你可以自己建立一个 OpenID 服务网站,也可以选择一个可信任的 OpenID 服务网站来完成注册)。
与OpenID同属性的身份识别服务商还有ⅥeID,ClaimID,CardSpace,Rapleaf,Trufina ID Card等,其中ⅥeID通用账户的应用最为广泛。
综述
个人认为现阶段需求,权限的操作粒度能控制在路径及按钮上,数据粒度通过sql实现。Shrio简单够用。
至于OAuth,OpenID 站点间统一登录功能,现租户与各个产品间单点登录已经通过cookies实现,所以Spring Security的这两个功能可以不考虑。
SpringSide网站的权限也是用Shrio做的。
---------------------------------------------------------------------------------------------------------------------
接着我们来说shiro的使用吧!
源博客地址是:http://peirenlei.iteye.com/blog/2086639
---------------------------------------------------------------------------------------------------------------------
我们采用下面的逻辑创建权限表结构(不是绝对的,根据需要修改)
一个用户可以有多种角色(normal,manager,admin等等)
一个角色可以有多个用户(user1,user2,user3等等)
一个角色可以有多个权限(save,update,delete,query等等)
一个权限只属于一个角色(delete只属于manager角色)
我们创建四张表:
t_user用户表:设置了3个用户
-------------------------------
id + username + password
---+----------------+----------
1 + tom + 000000
2 + jack + 000000
3 + rose + 000000
---------------------------------
t_role角色表:设置3个角色
--------------
id + rolename
---+----------
1 + admin
2 + manager
3 + normal
--------------
t_user_role用户角色表:tom是admin和normal角色,jack是manager和normal角色,rose是normal角色
---------------------
user_id + role_id
-----------+-----------
1 + 1
1 + 3
2 + 2
2 + 3
3 + 3
---------------------
t_permission权限表:admin角色可以删除,manager角色可以添加和更新,normal角色可以查看
-----------------------------------
id + permissionname + role_id
----+------------------------+-----------
1 + add + 2
2 + del + 1
3 + update + 2
4 + query + 3
-----------------------------------
建立对应的POJO:
- package com.cn.pojo;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- import javax.persistence.Transient;
- import org.hibernate.validator.constraints.NotEmpty;
- @Entity
- public class User {
- private Integer id;
- @NotEmpty(message="用户名不能为空")
- private String username;
- @NotEmpty(message="密码不能为空")
- private String password;
- private List<Role> roleList;//一个用户具有多个角色
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- public Integer getId() {
- return id;
- public void setId(Integer 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;
- @ManyToMany
- @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},inverseJoinColumns={@JoinColumn(name="role_id")})
- public List<Role> getRoleList() {
- return roleList;
- public void setRoleList(List<Role> roleList) {
- this.roleList = roleList;
- @Transient
- public Set<String> getRolesName(){
- Set<String> set=new HashSet<String>();
- for (Role role : roles) {
- }
- return set;
- }
- package com.cn.pojo;
- import java.util.ArrayList;
- import java.util.List;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.OneToMany;
- import javax.persistence.Table;
- import javax.persistence.Transient;
- @Entity
- public class Role {
- private Integer id;
- private String rolename;
- private List<Permission> permissionList;//一个角色对应多个权限
- private List<User> userList;//一个角色对应多个用户
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- public Integer getId() {
- return id;
- public void setId(Integer id) {
- this.id = id;
- public String getRolename() {
- return rolename;
- public void setRolename(String rolename) {
- this.rolename = rolename;
- @OneToMany(mappedBy="role")
- public List<Permission> getPermissionList() {
- return permissionList;
- public void setPermissionList(List<Permission> permissionList) {
- this.permissionList = permissionList;
- @ManyToMany
- @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="role_id")},inverseJoinColumns={@JoinColumn(name="user_id")})
- public List<User> getUserList() {
- return userList;
- public void setUserList(List<User> userList) {
- this.userList = userList;
- @Transient
- public List<String> getPermissionsName(){
- new ArrayList<String>();
- for (Permission per : perlist) {
- }
- return list;
- }
- package com.cn.pojo;
- 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
- public class Permission {
- private Integer id;
- private String permissionname;
- private Role role;//一个权限对应一个角色
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- public Integer getId() {
- return id;
- public void setId(Integer id) {
- this.id = id;
- public String getPermissionname() {
- return permissionname;
- public void setPermissionname(String permissionname) {
- this.permissionname = permissionname;
- @ManyToOne
- @JoinColumn(name="role_id")
- public Role getRole() {
- return role;
- public void setRole(Role role) {
- this.role = role;
- }
使用SHIRO的步骤:
1,导入jar
2,配置web.xml
3,建立dbRelm
4,在Spring中配置
pom.xml中配置如下:
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.hyx</groupId>
- <artifactId>springmvc</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>springmvc Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <!-- SpringMVC核心jar -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <!-- springmvc连接数据库需要的jar -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <!-- ************************************ -->
- <!-- Hibernate相关jar -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>4.2.5.Final</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-ehcache</artifactId>
- <version>4.2.5.Final</version>
- </dependency>
- <dependency>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache</artifactId>
- <version>2.7.2</version>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.4</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.26</version>
- </dependency>
- <!-- javax提供的annotation -->
- <dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <version>1</version>
- </dependency>
- <!-- **************************** -->
- <!-- hibernate验证 -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>5.0.1.Final</version>
- </dependency>
- <!-- 用于对@ResponseBody注解的支持 -->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.13</version>
- </dependency>
- <!-- 提供对c标签的支持 -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <!-- servlet api -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- </dependency>
- <!--Apache Shiro所需的jar包-->
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-web</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.2.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>springmvc</finalName>
- <!-- maven的jetty服务器插件 -->
- <plugins>
- <plugin>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-maven-plugin</artifactId>
- <configuration>
- <scanIntervalSeconds>10</scanIntervalSeconds>
- <webApp>
- <contextPath>/</contextPath>
- </webApp>
- <!-- 修改jetty的默认端口 -->
- <connectors>
- <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
- <port>80</port>
- <maxIdleTime>60000</maxIdleTime>
- </connector>
- </connectors>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
web.xml中的配置:
- <?xml version="1.0" encoding="UTF-8" ?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- >
- <display-name>Archetype Created Web Application</display-name>
- <!-- spring-orm-hibernate4的OpenSessionInViewFilter -->
- <filter>
- <filter-name>opensessioninview</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>opensessioninview</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 配置springmvc servlet -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <!-- / 表示所有的请求都要经过此serlvet -->
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- spring的监听器 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>
- </listener-class>
- </listener>
- <!-- Shiro配置 -->
- <filter>
- <filter-name>shiroFilter</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>shiroFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
- package com.cn.service;
- import java.util.List;
- import javax.inject.Inject;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.SimpleAuthenticationInfo;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.cn.pojo.Role;
- import com.cn.pojo.User;
- @Service
- public class MyShiro extends AuthorizingRealm{
- @Inject
- private UserService userService;
- /**
- * 权限认证
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- //获取登录时输入的用户名
- //到数据库查是否有此对象
- if(user!=null){
- //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
- new SimpleAuthorizationInfo();
- //用户的角色集合
- //用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要
- for (Role role : roleList) {
- }
- return info;
- return null;
- /**
- * 登录认证;
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(
- throws AuthenticationException {
- //UsernamePasswordToken对象用来存放提交的登录信息
- //查出是否有此用户
- if(user!=null){
- //若存在,将此用户存放到登录认证info中
- return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
- return null;
- }
在spring的配置文件中配置,为了区别spring原配置和shiro我们将shiro的配置独立出来。
applicationContext-shiro.xml
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 配置权限管理器 -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <!-- ref对应我们写的realm MyShiro -->
- <property name="realm" ref="myShiro"/>
- <!-- 使用下面配置的缓存管理器 -->
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
- <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <!-- 调用我们配置的权限管理器 -->
- <property name="securityManager" ref="securityManager"/>
- <!-- 配置我们的登录请求地址 -->
- <property name="loginUrl" value="/login"/>
- <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
- <property name="successUrl" value="/user"/>
- <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
- <property name="unauthorizedUrl" value="/403"/>
- <!-- 权限配置 -->
- <property name="filterChainDefinitions">
- <value>
- <!-- anon表示此地址不需要任何权限即可访问 -->
- <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->
- user=perms[user:query]
- <!-- roles[manager]表示访问此连接需要用户的角色为manager -->
- add=roles[manager]
- /user/edit/**=roles[manager]
- <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->
- </value>
- </property>
- </bean>
- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
- </beans>
用于登录,登出,权限跳转的控制:
- package com.cn.controller;
- import javax.validation.Valid;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.validation.BindingResult;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- import com.cn.pojo.User;
- @Controller
- public class HomeController {
- @RequestMapping(value="/login",method=RequestMethod.GET)
- public String loginForm(Model model){
- "user", new User());
- return "/login";
- @RequestMapping(value="/login",method=RequestMethod.POST)
- public String login(@Valid User user,BindingResult bindingResult,RedirectAttributes redirectAttributes){
- try {
- if(bindingResult.hasErrors()){
- return "/login";
- //使用权限工具进行用户登录,登录成功后跳到shiro配置的successUrl中,与下面的return没什么关系!
- new UsernamePasswordToken(user.getUsername(), user.getPassword()));
- return "redirect:/user";
- catch (AuthenticationException e) {
- "message","用户名或密码错误");
- return "redirect:/login";
- }
- @RequestMapping(value="/logout",method=RequestMethod.GET)
- public String logout(RedirectAttributes redirectAttributes ){
- //使用权限管理工具进行用户的退出,跳出登录,给出提示信息
- redirectAttributes.addFlashAttribute("message", "您已安全退出");
- return "redirect:/login";
- @RequestMapping("/403")
- public String unauthorizedRole(){
- return "/403";
- }
三个主要的JSP:
login.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- >
- <html>
- <head>
- <title>My JSP 'MyJsp.jsp' starting page</title>
- </head>
- <body>
- <h1>登录页面----${message }</h1>
- <img alt="" src="/static/img/1.jpg">
- <form:form action="/login" commandName="user" method="post">
- <form:input path="username"/> <form:errors path="username" cssClass="error"/> <br/>
- <form:password path="password"/> <form:errors path="password" cssClass="error" /> <br/>
- <form:button name="button">submit</form:button>
- </form:form>
- </body>
- </html>
user.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- >
- <html>
- <head>
- <title>用户列表</title>
- </head>
- <body>
- <h1>${message }</h1>
- <h1>用户列表--<a href="/user/add">添加用户</a>---<a href="/logout">退出登录</a> </h1>
- <h2>权限列表</h2>
- <shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>
- <shiro:hasRole name="manager">manager角色登录显示此内容</shiro:hasRole>
- <shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>
- <shiro:hasRole name="normal">normal角色登录显示此内容</shiro:hasRole>
- <shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>
- <shiro:principal/>-显示当前登录用户名
- <shiro:hasPermission name="add">add权限用户显示此内容</shiro:hasPermission>
- <shiro:hasPermission name="user:query">query权限用户显示此内容<shiro:principal/></shiro:hasPermission>
- <shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>
- <ul>
- <c:forEach items="${userList }" var="user">
- <li>用户名:${user.username }----密码:${user.password }----<a href="/user/edit/${user.id}">修改用户</a>----<a href="javascript:;" class="del" ref="${user.id }">删除用户</a></li>
- </c:forEach>
- </ul>
- <img alt="" src="/static/img/1.jpg">
- <script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script>
- <script>
- $(".del").click(function(){
- id=$(this).attr("ref");
- type:"delete",
- });
- });
- </script>
- </body>
- </html>
403.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- >
- <html>
- <head>
- <title>权限错误</title>
- </head>
- <body>
- <h1>对不起,您没有权限请求此连接!</h1>
- <img alt="" src="/static/img/1.jpg">
- </body>
- </html>
----------------------------------------------------------------------------------------------------------------
OK,到这里shiro就结束了!现在我们来看Spring Security的。
源:http://hotstrong.iteye.com/blog/1160153
----------------------------------------------------------------------------------------------------------------
使用Spring Security实现权限管理
1、技术目标
- 了解并创建Security框架所需数据表
- 为项目添加Spring Security框架
- 掌握Security框架配置
- 应用Security框架为项目的CRUD操作绑定权限
注意:本文所用项目为"影片管理",参看
http://hotstrong.iteye.com/blog/1156785
2、权限管理需求描述
- 为系统中的每个操作定义权限,如定义4个权限:
1)超级权限,可以使用所有操作
2)添加影片权限
3)修改影片权限
4)删除影片权限 - 为系统设置管理员帐号、密码
- 为系统创建权限组,每个权限组可以配置多个操作权限,如创建2个权限组:
1)"Administrator"权限组,具有超级权限
2)"影片维护"权限组,具有添加影片、修改影片权限 - 可将管理员加入权限组,管理员登录后具备权限组所对应操作权限
- 管理员可不属于某权限组,可为管理员直接分配权限
3、使用准备
3.1)在数据库中创建6张表
t_admin 管理员帐号表
t_role权限表
t_group 权限组表
t_group_role权限组对应权限表
t_group_user管理员所属权限组表
t_user_role管理员对应权限表
建表SQL语句如下:
- SET FOREIGN_KEY_CHECKS=0;
- ------------------------------
- -- 创建管理员帐号表t_admin
- -- ----------------------------
- CREATE TABLE `t_admin` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- varchar(12) NOT NULL DEFAULT '' COMMENT '用户密码',
- varchar(20) NOT NULL DEFAULT '' COMMENT '用户名字',
- varchar(32) NOT NULL DEFAULT '' COMMENT '电话号码',
- PRIMARY KEY (`id`)
- DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- 添加3个管理帐号
- -- ----------------------------
- INSERT INTO `t_admin` VALUES ('1', 'admin', 'admin', '');
- INSERT INTO `t_admin` VALUES ('4', '123456', 'test', '');
- INSERT INTO `t_admin` VALUES ('5', '111111', '111111', '');
- -- ----------------------------
- -- 创建权限表t_role
- -- ----------------------------
- CREATE TABLE `t_role` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- varchar(40) NOT NULL DEFAULT '',
- varchar(40) NOT NULL DEFAULT '' COMMENT '角色描述',
- varchar(40) NOT NULL DEFAULT '' COMMENT '分类',
- PRIMARY KEY (`id`)
- DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- 加入4个操作权限
- -- ----------------------------
- INSERT INTO `t_role` VALUES ('1', 'ROLE_ADMIN', '系统管理员', '系统管理员');
- INSERT INTO `t_role` VALUES ('2', 'ROLE_UPDATE_FILM', '修改', '影片管理');
- INSERT INTO `t_role` VALUES ('3', 'ROLE_DELETE_FILM', '删除', '影片管理');
- INSERT INTO `t_role` VALUES ('4', 'ROLE_ADD_FILM', '添加', '影片管理');
- -- ----------------------------
- -- 创建权限组表
- -- ----------------------------
- CREATE TABLE `t_group` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- varchar(50) NOT NULL DEFAULT '',
- PRIMARY KEY (`id`)
- DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- 添加2个权限组
- -- ----------------------------
- INSERT INTO `t_group` VALUES ('1', 'Administrator');
- INSERT INTO `t_group` VALUES ('2', '影片维护');
- -- ----------------------------
- -- 创建权限组对应权限表t_group_role
- -- ----------------------------
- CREATE TABLE `t_group_role` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- bigint(20) unsigned NOT NULL,
- bigint(20) unsigned NOT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `groupid2` (`groupid`,`roleid`),
- KEY `roleid` (`roleid`),
- CONSTRAINT `t_group_role_ibfk_1` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
- CONSTRAINT `t_group_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
- DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- 加入权限组与权限的对应关系
- -- ----------------------------
- INSERT INTO `t_group_role` VALUES ('1', '1', '1');
- INSERT INTO `t_group_role` VALUES ('2', '2', '2');
- INSERT INTO `t_group_role` VALUES ('4', '2', '4');
- -- ----------------------------
- -- 创建管理员所属权限组表t_group_user
- -- ----------------------------
- CREATE TABLE `t_group_user` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- bigint(20) unsigned NOT NULL,
- bigint(20) unsigned NOT NULL,
- PRIMARY KEY (`id`),
- KEY `userid` (`userid`),
- KEY `groupid` (`groupid`),
- CONSTRAINT `t_group_user_ibfk_2` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
- CONSTRAINT `t_group_user_ibfk_3` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`)
- DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- 将管理员加入权限组
- -- ----------------------------
- INSERT INTO `t_group_user` VALUES ('1', '1', '1');
- INSERT INTO `t_group_user` VALUES ('2', '4', '2');
- -- ----------------------------
- -- 创建管理员对应权限表t_user_role
- -- 设置该表可跳过权限组,为管理员直接分配权限
- -- ----------------------------
- CREATE TABLE `t_user_role` (
- bigint(20) unsigned NOT NULL AUTO_INCREMENT,
- bigint(20) unsigned NOT NULL,
- bigint(20) unsigned NOT NULL,
- PRIMARY KEY (`id`),
- KEY `userid` (`userid`),
- KEY `roleid` (`roleid`),
- CONSTRAINT `t_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`),
- CONSTRAINT `t_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
- DEFAULT CHARSET=utf8;
3.2)在项目中新增如下jar包(security框架所需jar包):
注意:以下jar包本文已提供下载
spring-security-config-3.1.0.RC2.jar
spring-security-core-3.1.0.RC2.jar
spring-security-taglibs-3.1.0.RC2.jar
spring-security-web-3.1.0.RC2.jar
3.3)创建如下包,放置登录验证过滤器代码:
com.xxx.security
3.4)在src下创建Spring配置文件applicationContext-security.xml,内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
- 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-3.0.xsd
- >
- <!-- 这里进行配置 -->
- </beans:beans>
3.5)在web.xml中加入security配置,如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- >
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
- </context-param>
- <!-- 配置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>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
4、站点根路径下创建登录页面login.jsp,代码如下:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%
- path = request.getContextPath();
- basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
- >
- >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>后台登录</title>
- </head>
- <body onload="document.loginForm.j_username.focus();">
- <!-- 登录表单 -->
- <form name="loginForm" action="<c:url value='/j_spring_security_check'/>" method="post">
- <!-- 登录失败后,显示之前的登录名 -->
- <input type='text' name='j_username' class="txtinput"
- value='<c:if test="${not empty param.login_error}" >
- <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />
- <br />
- <input type='password' name='j_password' class="txtinput" />
- <br />
- <input type="checkbox" name="_spring_security_remember_me" />
- <input name="submit" type="submit" value="提交" />
- <input name="reset" type="reset" value="重置" />
- </form>
- <br />
- <!-- 显示登录失败原因 -->
- <c:if test="${not empty param.error}">
- <font color="red"> 登录失败<br />
- <br />
- <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />. </font>
- </c:if>
- </body>
- </html>
5、站点根路径下创建注销页面loggedout.jsp,代码如下:
- <%@page session="false" %>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <%@ page pageEncoding="UTF-8"%>
- <%
- path = request.getContextPath();
- basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
- >
- >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
- <title>登出</title>
- </head>
- <body>
- <a href="<c:url value='/login.jsp'/>">点击这里登录</a>
- </body>
- </html>
6、站点根路径下创建HttpSession超时提示页面timeout.jsp,代码如下:
- <%@page session="false" %>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
- <%
- path = request.getContextPath();
- basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
- >
- >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>用户失效</title>
- </head>
- <body>
- <br />
- <a href="<c:url value='/login.jsp'/>" >
- </a>
- </body>
- </html>
7、在com.xxx.security包下创建登录验证过滤器,该过滤器可用于在管理员登录时进行日志记录等相关操作,包括两个类:
- LoginUsernamePasswordAuthenticationFilter
- LoginSuccessHandler
7.1)LoginUsernamePasswordAuthenticationFilter代码如下:
- package com.xxx.security;
- import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
- public class LoginUsernamePasswordAuthenticationFilter extends
- }
7.2)LoginSuccessHandler代码如下:
- package com.xxx.security;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
- /**
- * 处理管理员登录日志
- *
- */
- public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
- @Override
- public void onAuthenticationSuccess(HttpServletRequest request,
- throws IOException,
- //输出登录提示信息
- "管理员 " + userDetails.getUsername() + " 登录");
- super.onAuthenticationSuccess(request, response, authentication);
- }
8、在applicationContext-security.xml中加入权限管理配置,如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
- 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-3.0.xsd
- >
- <http >
- <!-- 不拦截login.jsp -->
- <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
- <!--仅拦截到manager下面的内容,具备access对应权限的-->
- <intercept-url pattern="/manager/**" access="ROLE_ADMIN,ROLE_UPDATE_FILM,ROLE_DELETE_FILM,ROLE_ADD_FILM" />
- <!-- 设置登录过滤器 -->
- <custom-filter before="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter" />
- <!-- 登录表单设置 -->
- <form-login login-page="/login.jsp"
- default-target-url="/manager/films.jsp"
- authentication-failure-url="/login.jsp?error=true" />
- <!-- 登出操作后跳转到该页面 -->
- <logout logout-success-url="/loggedout.jsp"
- delete-cookies="JSESSIONID" />
- <remember-me />
- <!-- SESSION超时后跳转到该页面 -->
- <session-management invalid-session-url="/timeout.jsp">
- </session-management>
- </http>
- <authentication-manager alias="authenticationManager">
- <authentication-provider>
- 直接使用SQL语句查询登录帐号对应权限,
- authorities-by-username-query:查询登录用户权限(登录用户可以不属于任何组,从t_user_role表中获取权限)
- -->
- <jdbc-user-service data-source-ref="dataSource"
- group-authorities-by-username-query="SELECT g.id,g.groupname,role.role
- LEFT OUTER JOIN t_group_role AS grouprole ON (g.id = grouprole.groupid)
- role.id = grouprole.roleid)
- g.id = groupuser.groupid)
- t_admin.id = groupuser.userid)
- t_admin.nickname = ?"
- users-by-username-query="SELECT t_admin.nickname AS username,t_admin.passwd as password,'true' AS enabled
- WHERE t_admin.nickname = ?"
- authorities-by-username-query="SELECT t_admin.nickname AS username,role.role as authorities
- LEFT OUTER JOIN t_user_role AS userrole ON(t_admin.id = userrole.userid)
- userrole.roleid = role.id)
- t_admin.nickname = ?" />
- </authentication-provider>
- </authentication-manager>
- <!-- 自定义消息 -->
- <b:bean id="messageSource"
- class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
- <b:property name="basename"
- value="classpath:org/springframework/security/messages" />
- </b:bean>
- <!-- 定制登录过滤器 -->
- <beans:bean id="loginSuccessHandler" class="com.xxx.security.LoginSuccessHandler">
- <b:property name="defaultTargetUrl">
- <!-- 登录成功后转发到该页面 -->
- <b:value>/manager/films.jsp</b:value>
- </b:property>
- </beans:bean>
- <beans:bean id="authenticationProcessingFilter" class="com.xxx.security.LoginUsernamePasswordAuthenticationFilter">
- <beans:property name="authenticationSuccessHandler" ref="loginSuccessHandler"></beans:property>
- <beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"></beans:property>
- <beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
- </beans:bean>
- <beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
- <beans:property name="defaultFailureUrl">
- <!-- 登录失败后转发到该页面 -->
- <beans:value>/login.jsp?error=true</beans:value>
- </beans:property>
- </beans:bean>
- </beans:beans>
注:
Spring Security 默认action="j_spring_security_check",让很多人不理解这个请求之后会跳转到哪里去,
这里我们就看
配置文件里这个<http></http>标签,这个标签里面最基本的是intercept-url,用来设置访问权限的。
<http></http>标签里面有个form-login 标签,这个标签有很多属性,大概情况如下:
form-login属性详解
1. login-page 自定义登录页url,默认为/login
2. login-processing-url 登录请求拦截的url,也就是form表单提交时指定的action
3. default-target-url 默认登录成功后跳转的url
4. always-use-default-target 是否总是使用默认的登录成功后跳转url
5. authentication-failure-url 登录失败后跳转的url
6. username-parameter 用户名的请求字段 默认为userName
7. password-parameter 密码的请求字段 默认为password
8. authentication-success-handler-ref 指向一个AuthenticationSuccessHandler用于处理认证成功的请求,不能和default-target-url还有always-use-default-target同时使用
9. authentication-success-forward-url 用于authentication-failure-handler-ref
10. authentication-failure-handler-ref 指向一个AuthenticationFailureHandler用于处理失败的认证请求
11. authentication-failure-forward-url 用于authentication-failure-handler-ref
12. authentication-details-source-ref 指向一个AuthenticationDetailsSource,在认证过滤器中使用
9、为影片页面films.jsp定制操作权限,定制后,不同的帐号登录会看到不同的操作,
比如,帐号"admin"属于权限组"Administrator",具备权限"ROLE_ADMIN",登录后
可以看到所有操作,帐号"test"属于权限组"影片维护",具备权限"ROLE_UPDATE_FILM"
和"ROLE_ADD_FILM",登录后只能看到"添加影片信息"和"修改"操作
films.jsp页面权限分布图:
films.jsp代码如下:
- <%@ page language="java" contentType="text/html; charset=utf-8"
- >
- <%@taglib uri="/struts-tags" prefix="s" %>
- <%@ taglib prefix="security"
- uri="http://www.springframework.org/security/tags"%>
- <%
- path = request.getContextPath();
- basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- >
- >
- <html>
- <head>
- <title>信息操作</title>
- </head>
- <body>
- <s:form action="/film/findFilm" method="post">
- <s:submit value=" 获取所有影片信息 "></s:submit>
- </s:form>
- <!-- 添加影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_ADD_FILM权限可以执行 -->
- <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_ADD_FILM">
- <a href="<%=basePath %>manager/insertFilm.jsp">添加影片信息</a><br />
- </security:authorize>
- <s:if test="filmList != null">
- <table border="1" width="40%">
- <tr>
- <th>序号</th><th>影片名</th><th>操作</th>
- </tr>
- <%-- 遍历影片信息 --%>
- <s:iterator var="film" value="filmList" status="st">
- <tr>
- <td><s:property value="#st.index+1" /></td>
- <td><s:property value="fname" /></td>
- <td>
- <!-- 修改影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_UPDATE_FILM权限可以执行 -->
- <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_UPDATE_FILM">
- <s:url id="detailUrl" value="/film/detailFilm">
- <s:param name="id" value="%{id}"/>
- </s:url>
- <s:a href="%{detailUrl}">[修改]</s:a>
- </security:authorize>
- <!-- 删除影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_DELETE_FILM权限可以执行 -->
- <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_DELETE_FILM">
- <s:url id="deleteUrl" value="/film/deleteFilm">
- <s:param name="id" value="%{id}"/>
- </s:url>
- <s:a href="%{deleteUrl}">[删除]</s:a>
- </security:authorize>
- </td>
- </tr>
- </s:iterator>
- </table>
- </s:if>
- </body>
- </html>
Shrio在线教程:
http://www.sojson.com/jc/shiro.html
Shiro + Redis 源码