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:**
Java代码
1. package com.cn.pojo;
3. import java.util.HashSet;
4. import java.util.List;
5. import java.util.Set;
7. import javax.persistence.Entity;
8. import javax.persistence.GeneratedValue;
9. import javax.persistence.GenerationType;
10. import javax.persistence.Id;
11. import javax.persistence.JoinColumn;
12. import javax.persistence.JoinTable;
13. import javax.persistence.ManyToMany;
14. import javax.persistence.Table;
15. import javax.persistence.Transient;
17. import org.hibernate.validator.constraints.NotEmpty;
19. @Entity
20. @Table(name="t_user")
21. public class User {
23. private Integer id;
24. @NotEmpty(message="用户名不能为空")
25. private String username;
26. @NotEmpty(message="密码不能为空")
27. private String password;
28. private List<Role> roleList;//一个用户具有多个角色
30. @Id
31. @GeneratedValue(strategy=GenerationType.IDENTITY)
32. public Integer getId() {
33. return id;
34. }
35. public void setId(Integer id) {
36. this.id = id;
37. }
38. public String getUsername() {
39. return username;
40. }
41. public void setUsername(String username) {
42. this.username = username;
43. }
44. public String getPassword() {
45. return password;
46. }
47. public void setPassword(String password) {
48. this.password = password;
49. }
50. @ManyToMany
51. @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},inverseJoinColumns={@JoinColumn(name="role_id")})
52. public List<Role> getRoleList() {
53. return roleList;
54. }
55. public void setRoleList(List<Role> roleList) {
56. this.roleList = roleList;
57. }
59. @Transient
60. public Set<String> getRolesName(){
61. List<Role> roles=getRoleList();
62. Set<String> set=new HashSet<String>();
63. for (Role role : roles) {
64. set.add(role.getRolename());
65. }
66. return set;
67. }
69. }
Java代码
1. package com.cn.pojo;
3. import java.util.ArrayList;
4. import java.util.List;
6. import javax.persistence.Entity;
7. import javax.persistence.GeneratedValue;
8. import javax.persistence.GenerationType;
9. import javax.persistence.Id;
10. import javax.persistence.JoinColumn;
11. import javax.persistence.JoinTable;
12. import javax.persistence.ManyToMany;
13. import javax.persistence.OneToMany;
14. import javax.persistence.Table;
15. import javax.persistence.Transient;
17. @Entity
18. @Table(name="t_role")
19. public class Role {
21. private Integer id;
22. private String rolename;
23. private List<Permission> permissionList;//一个角色对应多个权限
24. private List<User> userList;//一个角色对应多个用户
26. @Id
27. @GeneratedValue(strategy=GenerationType.IDENTITY)
28. public Integer getId() {
29. return id;
30. }
31. public void setId(Integer id) {
32. this.id = id;
33. }
34. public String getRolename() {
35. return rolename;
36. }
37. public void setRolename(String rolename) {
38. this.rolename = rolename;
39. }
40. @OneToMany(mappedBy="role")
41. public List<Permission> getPermissionList() {
42. return permissionList;
43. }
44. public void setPermissionList(List<Permission> permissionList) {
45. this.permissionList = permissionList;
46. }
47. @ManyToMany
48. @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="role_id")},inverseJoinColumns={@JoinColumn(name="user_id")})
49. public List<User> getUserList() {
50. return userList;
51. }
52. public void setUserList(List<User> userList) {
53. this.userList = userList;
54. }
56. @Transient
57. public List<String> getPermissionsName(){
58. List<String> list=new ArrayList<String>();
59. List<Permission> perlist=getPermissionList();
60. for (Permission per : perlist) {
61. list.add(per.getPermissionname());
62. }
63. return list;
64. }
65. }
Java代码
1. package com.cn.pojo;
3. import javax.persistence.Entity;
4. import javax.persistence.GeneratedValue;
5. import javax.persistence.GenerationType;
6. import javax.persistence.Id;
7. import javax.persistence.JoinColumn;
8. import javax.persistence.ManyToOne;
9. import javax.persistence.Table;
11. @Entity
12. @Table(name="t_permission")
13. public class Permission {
15. private Integer id;
16. private String permissionname;
17. private Role role;//一个权限对应一个角色
19. @Id
20. @GeneratedValue(strategy=GenerationType.IDENTITY)
21. public Integer getId() {
22. return id;
23. }
24. public void setId(Integer id) {
25. this.id = id;
26. }
27. public String getPermissionname() {
28. return permissionname;
29. }
30. public void setPermissionname(String permissionname) {
31. this.permissionname = permissionname;
32. }
33. @ManyToOne
34. @JoinColumn(name="role_id")
35. public Role getRole() {
36. return role;
37. }
38. public void setRole(Role role) {
39. this.role = role;
40. }
42. }
使用SHIRO的步骤:
1,导入jar
2,配置web.xml
3,建立dbRelm
4,在Spring中配置
pom.xml中配置如下:
Xml代码
1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3. <modelVersion>4.0.0</modelVersion>
4. <groupId>com.hyx</groupId>
5. <artifactId>springmvc</artifactId>
6. <packaging>war</packaging>
7. <version>0.0.1-SNAPSHOT</version>
8. <name>springmvc Maven Webapp</name>
9. <url>http://maven.apache.org</url>
10. <dependencies>
11. <dependency>
12. <groupId>junit</groupId>
13. <artifactId>junit</artifactId>
14. <version>3.8.1</version>
15. <scope>test</scope>
16. </dependency>
17. <!-- SpringMVC核心jar -->
18. <dependency>
19. <groupId>org.springframework</groupId>
20. <artifactId>spring-webmvc</artifactId>
21. <version>3.2.4.RELEASE</version>
22. </dependency>
23. <!-- springmvc连接数据库需要的jar -->
24. <dependency>
25. <groupId>org.springframework</groupId>
26. <artifactId>spring-jdbc</artifactId>
27. <version>3.2.4.RELEASE</version>
28. </dependency>
29. <dependency>
30. <groupId>org.springframework</groupId>
31. <artifactId>spring-orm</artifactId>
32. <version>3.2.4.RELEASE</version>
33. </dependency>
34. <!-- ************************************ -->
35. <!-- Hibernate相关jar -->
36. <dependency>
37. <groupId>org.hibernate</groupId>
38. <artifactId>hibernate-core</artifactId>
39. <version>4.2.5.Final</version>
40. </dependency>
41. <dependency>
42. <groupId>org.hibernate</groupId>
43. <artifactId>hibernate-ehcache</artifactId>
44. <version>4.2.5.Final</version>
45. </dependency>
46. <dependency>
47. <groupId>net.sf.ehcache</groupId>
48. <artifactId>ehcache</artifactId>
49. <version>2.7.2</version>
50. </dependency>
51. <dependency>
52. <groupId>commons-dbcp</groupId>
53. <artifactId>commons-dbcp</artifactId>
54. <version>1.4</version>
55. </dependency>
56. <dependency>
57. <groupId>mysql</groupId>
58. <artifactId>mysql-connector-java</artifactId>
59. <version>5.1.26</version>
60. </dependency>
61. <!-- javax提供的annotation -->
62. <dependency>
63. <groupId>javax.inject</groupId>
64. <artifactId>javax.inject</artifactId>
65. <version>1</version>
66. </dependency>
67. <!-- **************************** -->
69. <!-- hibernate验证 -->
70. <dependency>
71. <groupId>org.hibernate</groupId>
72. <artifactId>hibernate-validator</artifactId>
73. <version>5.0.1.Final</version>
74. </dependency>
75. <!-- 用于对@ResponseBody注解的支持 -->
76. <dependency>
77. <groupId>org.codehaus.jackson</groupId>
78. <artifactId>jackson-mapper-asl</artifactId>
79. <version>1.9.13</version>
80. </dependency>
81. <!-- 提供对c标签的支持 -->
82. <dependency>
83. <groupId>javax.servlet</groupId>
84. <artifactId>jstl</artifactId>
85. <version>1.2</version>
86. </dependency>
87. <!-- servlet api -->
88. <dependency>
89. <groupId>javax.servlet</groupId>
90. <artifactId>servlet-api</artifactId>
91. <version>2.5</version>
92. </dependency>
94. <!--Apache Shiro所需的jar包-->
95. <dependency>
96. <groupId>org.apache.shiro</groupId>
97. <artifactId>shiro-core</artifactId>
98. <version>1.2.2</version>
99. </dependency>
100. <dependency>
101. <groupId>org.apache.shiro</groupId>
102. <artifactId>shiro-web</artifactId>
103. <version>1.2.2</version>
104. </dependency>
105. <dependency>
106. <groupId>org.apache.shiro</groupId>
107. <artifactId>shiro-spring</artifactId>
108. <version>1.2.2</version>
109. </dependency>
110. </dependencies>
112. <build>
113. <finalName>springmvc</finalName>
114. <!-- maven的jetty服务器插件 -->
115. <plugins>
116. <plugin>
117. <groupId>org.mortbay.jetty</groupId>
118. <artifactId>jetty-maven-plugin</artifactId>
119. <configuration>
120. <scanIntervalSeconds>10</scanIntervalSeconds>
121. <webApp>
122. <contextPath>/</contextPath>
123. </webApp>
124. <!-- 修改jetty的默认端口 -->
125. <connectors>
126. <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
127. <port>80</port>
128. <maxIdleTime>60000</maxIdleTime>
129. </connector>
130. </connectors>
131. </configuration>
132. </plugin>
133. </plugins>
134. </build>
135. </project>
** web.xml中的配置:**
Xml代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <web-app version="2.5"
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
7. <display-name>Archetype Created Web Application</display-name>
9. <!-- spring-orm-hibernate4的OpenSessionInViewFilter -->
10. <filter>
11. <filter-name>opensessioninview</filter-name>
12. <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>opensessioninview</filter-name>
16. <url-pattern>/*</url-pattern>
17. </filter-mapping>
19. <!-- 配置springmvc servlet -->
20. <servlet>
21. <servlet-name>springmvc</servlet-name>
22. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
23. <load-on-startup>1</load-on-startup>
24. </servlet>
25. <servlet-mapping>
26. <servlet-name>springmvc</servlet-name>
27. <!-- / 表示所有的请求都要经过此serlvet -->
28. <url-pattern>/</url-pattern>
29. </servlet-mapping>
31. <!-- spring的监听器 -->
32. <context-param>
33. <param-name>contextConfigLocation</param-name>
34. <param-value>classpath:applicationContext*.xml</param-value>
35. </context-param>
36. <listener>
37. <listener-class>
38. org.springframework.web.context.ContextLoaderListener
39. </listener-class>
40. </listener>
42. <!-- Shiro配置 -->
43. <filter>
44. <filter-name>shiroFilter</filter-name>
45. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
46. </filter>
47. <filter-mapping>
48. <filter-name>shiroFilter</filter-name>
49. <url-pattern>/*</url-pattern>
50. </filter-mapping>
52. </web-app>
Java代码
1. package com.cn.service;
3. import java.util.List;
5. import javax.inject.Inject;
7. import org.apache.shiro.authc.AuthenticationException;
8. import org.apache.shiro.authc.AuthenticationInfo;
9. import org.apache.shiro.authc.AuthenticationToken;
10. import org.apache.shiro.authc.SimpleAuthenticationInfo;
11. import org.apache.shiro.authc.UsernamePasswordToken;
12. import org.apache.shiro.authz.AuthorizationInfo;
13. import org.apache.shiro.authz.SimpleAuthorizationInfo;
14. import org.apache.shiro.realm.AuthorizingRealm;
15. import org.apache.shiro.subject.PrincipalCollection;
16. import org.springframework.stereotype.Service;
17. import org.springframework.transaction.annotation.Transactional;
19. import com.cn.pojo.Role;
20. import com.cn.pojo.User;
22. @Service
23. @Transactional
24. public class MyShiro extends AuthorizingRealm{
26. @Inject
27. private UserService userService;
28. /**
29. * 权限认证
30. */
31. @Override
32. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
33. //获取登录时输入的用户名
34. String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();
35. //到数据库查是否有此对象
36. User user=userService.findByName(loginName);
37. if(user!=null){
38. //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
39. SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
40. //用户的角色集合
41. info.setRoles(user.getRolesName());
42. //用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要
43. List<Role> roleList=user.getRoleList();
44. for (Role role : roleList) {
45. info.addStringPermissions(role.getPermissionsName());
46. }
47. return info;
48. }
49. return null;
50. }
52. /**
53. * 登录认证;
54. */
55. @Override
56. protected AuthenticationInfo doGetAuthenticationInfo(
57. AuthenticationToken authenticationToken) throws AuthenticationException {
58. //UsernamePasswordToken对象用来存放提交的登录信息
59. UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
60. //查出是否有此用户
61. User user=userService.findByName(token.getUsername());
62. if(user!=null){
63. //若存在,将此用户存放到登录认证info中
64. return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
65. }
66. return null;
67. }
69. }
在spring的配置文件中配置,为了区别spring原配置和shiro我们将shiro的配置独立出来。
applicationContext-shiro.xml
Xml代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:aop="http://www.springframework.org/schema/aop"
5. xmlns:tx="http://www.springframework.org/schema/tx"
6. xmlns:context="http://www.springframework.org/schema/context"
7. xsi:schemaLocation="
8. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
11. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
13. <!-- 配置权限管理器 -->
14. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
15. <!-- ref对应我们写的realm MyShiro -->
16. <property name="realm" ref="myShiro"/>
17. <!-- 使用下面配置的缓存管理器 -->
18. <property name="cacheManager" ref="cacheManager"/>
19. </bean>
21. <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
22. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
23. <!-- 调用我们配置的权限管理器 -->
24. <property name="securityManager" ref="securityManager"/>
25. <!-- 配置我们的登录请求地址 -->
26. <property name="loginUrl" value="/login"/>
27. <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
28. <property name="successUrl" value="/user"/>
29. <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
30. <property name="unauthorizedUrl" value="/403"/>
31. <!-- 权限配置 -->
32. <property name="filterChainDefinitions">
33. <value>
34. <!-- anon表示此地址不需要任何权限即可访问 -->
35. /static/**=anon
36. <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->
37. /user=perms[user:query]
38. <!-- roles[manager]表示访问此连接需要用户的角色为manager -->
39. /user/add=roles[manager]
40. /user/del/**=roles[admin]
41. /user/edit/**=roles[manager]
42. <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->
43. /** = authc
44. </value>
45. </property>
46. </bean>
49. <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
50. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
52. </beans>
** 用于登录,登出,权限跳转的控制:**
Java代码
1. package com.cn.controller;
3. import javax.validation.Valid;
5. import org.apache.shiro.SecurityUtils;
6. import org.apache.shiro.authc.AuthenticationException;
7. import org.apache.shiro.authc.UsernamePasswordToken;
8. import org.springframework.stereotype.Controller;
9. import org.springframework.ui.Model;
10. import org.springframework.validation.BindingResult;
11. import org.springframework.web.bind.annotation.RequestMapping;
12. import org.springframework.web.bind.annotation.RequestMethod;
13. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
15. import com.cn.pojo.User;
17. @Controller
18. public class HomeController {
20. @RequestMapping(value="/login",method=RequestMethod.GET)
21. public String loginForm(Model model){
22. model.addAttribute("user", new User());
23. return "/login";
24. }
26. @RequestMapping(value="/login",method=RequestMethod.POST)
27. public String login(@Valid User user,BindingResult bindingResult,RedirectAttributes redirectAttributes){
28. try {
29. if(bindingResult.hasErrors()){
30. return "/login";
31. }
32. //使用权限工具进行用户登录,登录成功后跳到shiro配置的successUrl中,与下面的return没什么关系!
33. SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
34. return "redirect:/user";
35. } catch (AuthenticationException e) {
36. redirectAttributes.addFlashAttribute("message","用户名或密码错误");
37. return "redirect:/login";
38. }
39. }
41. @RequestMapping(value="/logout",method=RequestMethod.GET)
42. public String logout(RedirectAttributes redirectAttributes ){
43. //使用权限管理工具进行用户的退出,跳出登录,给出提示信息
44. SecurityUtils.getSubject().logout();
45. redirectAttributes.addFlashAttribute("message", "您已安全退出");
46. return "redirect:/login";
47. }
49. @RequestMapping("/403")
50. public String unauthorizedRole(){
51. return "/403";
52. }
53. }
** 三个主要的JSP:
login.jsp:**
Html代码
1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4. <html>
5. <head>
6. <title>My JSP 'MyJsp.jsp' starting page</title>
7. </head>
9. <body>
10. <h1>登录页面----${message }</h1>
11. <img alt="" src="/static/img/1.jpg">
12. <form:form action="/login" commandName="user" method="post">
13. 用户名:<form:input path="username"/> <form:errors path="username" cssClass="error"/> <br/>
14. 密 码:<form:password path="password"/> <form:errors path="password" cssClass="error" /> <br/>
15. <form:button name="button">submit</form:button>
16. </form:form>
17. </body>
18. </html>
user.jsp:
Html代码
1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
5. <html>
6. <head>
7. <title>用户列表</title>
8. </head>
9. <body>
10. <h1>${message }</h1>
11. <h1>用户列表--<a href="/user/add">添加用户</a>---<a href="/logout">退出登录</a> </h1>
12. <h2>权限列表</h2>
13. <shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>
14. <shiro:hasRole name="manager">manager角色登录显示此内容</shiro:hasRole>
15. <shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>
16. <shiro:hasRole name="normal">normal角色登录显示此内容</shiro:hasRole>
18. <shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>
19. <shiro:principal/>-显示当前登录用户名
20. <shiro:hasPermission name="add">add权限用户显示此内容</shiro:hasPermission>
21. <shiro:hasPermission name="user:query">query权限用户显示此内容<shiro:principal/></shiro:hasPermission>
22. <shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>
23. <ul>
24. <c:forEach items="${userList }" var="user">
25. <li>用户名:${user.username }----密码:${user.password }----<a href="/user/edit/${user.id}">修改用户</a>----<a href="javascript:;" class="del" ref="${user.id }">删除用户</a></li>
26. </c:forEach>
27. </ul>
28. <img alt="" src="/static/img/1.jpg">
29. <script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script>
30. <script>
31. $(function(){
32. $(".del").click(function(){
33. var id=$(this).attr("ref");
34. $.ajax({
35. type:"delete",
36. url:"/user/del/"+id,
37. success:function(e){
39. }
40. });
41. });
42. });
43. </script>
44. </body>
45. </html>
403.jsp:
Html代码
1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4. <html>
5. <head>
6. <title>权限错误</title>
7. </head>
9. <body>
10. <h1>对不起,您没有权限请求此连接!</h1>
11. <img alt="" src="/static/img/1.jpg">
13. </body>
14. </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语句如下:
Sql代码 [图片上传失败...(image-1abd57-1560049661925)]
1. SET FOREIGN_KEY_CHECKS=0;
2. ------------------------------
3. -- 创建管理员帐号表t_admin
4. -- ----------------------------
5. CREATE TABLE `t_admin` (
6. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
7. `passwd` varchar(12) NOT NULL DEFAULT '' COMMENT '用户密码',
8. `nickname` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名字',
9. `phoneno` varchar(32) NOT NULL DEFAULT '' COMMENT '电话号码',
10. PRIMARY KEY (`id`)
11. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
- -- 添加3个管理帐号
16. INSERT INTO `t_admin` VALUES ('1', 'admin', 'admin', '');
17. INSERT INTO `t_admin` VALUES ('4', '123456', 'test', '');
18. INSERT INTO `t_admin` VALUES ('5', '111111', '111111', '');
- -- 创建权限表t_role
23. CREATE TABLE `t_role` (
24. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
25. `role` varchar(40) NOT NULL DEFAULT '',
26. `descpt` varchar(40) NOT NULL DEFAULT '' COMMENT '角色描述',
27. `category` varchar(40) NOT NULL DEFAULT '' COMMENT '分类',
28. PRIMARY KEY (`id`)
29. ) ENGINE=InnoDB AUTO_INCREMENT=60 DEFAULT CHARSET=utf8;
- -- 加入4个操作权限
34. INSERT INTO `t_role` VALUES ('1', 'ROLE_ADMIN', '系统管理员', '系统管理员');
35. INSERT INTO `t_role` VALUES ('2', 'ROLE_UPDATE_FILM', '修改', '影片管理');
36. INSERT INTO `t_role` VALUES ('3', 'ROLE_DELETE_FILM', '删除', '影片管理');
37. INSERT INTO `t_role` VALUES ('4', 'ROLE_ADD_FILM', '添加', '影片管理');
- -- 创建权限组表
42. CREATE TABLE `t_group` (
43. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
44. `groupname` varchar(50) NOT NULL DEFAULT '',
45. PRIMARY KEY (`id`)
46. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
- -- 添加2个权限组
51. INSERT INTO `t_group` VALUES ('1', 'Administrator');
52. INSERT INTO `t_group` VALUES ('2', '影片维护');
- -- 创建权限组对应权限表t_group_role
57. CREATE TABLE `t_group_role` (
58. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
59. `groupid` bigint(20) unsigned NOT NULL,
60. `roleid` bigint(20) unsigned NOT NULL,
61. PRIMARY KEY (`id`),
62. UNIQUE KEY `groupid2` (`groupid`,`roleid`),
63. KEY `roleid` (`roleid`),
64. CONSTRAINT `t_group_role_ibfk_1` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
65. CONSTRAINT `t_group_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
66. ) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;
- -- 加入权限组与权限的对应关系
71. INSERT INTO `t_group_role` VALUES ('1', '1', '1');
72. INSERT INTO `t_group_role` VALUES ('2', '2', '2');
73. INSERT INTO `t_group_role` VALUES ('4', '2', '4');
- -- 创建管理员所属权限组表t_group_user
78. CREATE TABLE `t_group_user` (
79. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
80. `userid` bigint(20) unsigned NOT NULL,
81. `groupid` bigint(20) unsigned NOT NULL,
82. PRIMARY KEY (`id`),
83. KEY `userid` (`userid`),
84. KEY `groupid` (`groupid`),
85. CONSTRAINT `t_group_user_ibfk_2` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
86. CONSTRAINT `t_group_user_ibfk_3` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`)
87. ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
- -- 将管理员加入权限组
92. INSERT INTO `t_group_user` VALUES ('1', '1', '1');
93. INSERT INTO `t_group_user` VALUES ('2', '4', '2');
- -- 创建管理员对应权限表t_user_role
- -- 设置该表可跳过权限组,为管理员直接分配权限
99. CREATE TABLE `t_user_role` (
100. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
101. `userid` bigint(20) unsigned NOT NULL,
102. `roleid` bigint(20) unsigned NOT NULL,
103. PRIMARY KEY (`id`),
104. KEY `userid` (`userid`),
105. KEY `roleid` (`roleid`),
106. CONSTRAINT `t_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`),
107. CONSTRAINT `t_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
108. ) ENGINE=InnoDB AUTO_INCREMENT=5 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代码 [图片上传失败...(image-77aad8-1560049661925)]
1. <?xml version="1.0" encoding="UTF-8"?>
3. <beans:beans xmlns="http://www.springframework.org/schema/security"
4. xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
9. <!-- 这里进行配置 -->
11. </beans:beans>
**3.5)在web.xml中加入security配置,如下:**
Xml代码 [图片上传失败...(image-9156bc-1560049661925)]
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5"
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
7. <welcome-file-list>
8. <welcome-file>index.jsp</welcome-file>
9. </welcome-file-list>
11. <context-param>
12. <param-name>contextConfigLocation</param-name>
13. <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
14. </context-param>
16. <!-- 配置Spring Security -->
17. <filter>
18. <filter-name>springSecurityFilterChain</filter-name>
19. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
20. </filter>
21. <filter-mapping>
22. <filter-name>springSecurityFilterChain</filter-name>
23. <url-pattern>/*</url-pattern>
24. </filter-mapping>
26. <filter>
27. <filter-name>struts2</filter-name>
28. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
29. </filter>
30. <filter-mapping>
31. <filter-name>struts2</filter-name>
32. <url-pattern>/*</url-pattern>
33. </filter-mapping>
34. <listener>
35. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
36. </listener>
37. </web-app>
**4、站点根路径下创建登录页面login.jsp,代码如下:**
Html代码 [图片上传失败...(image-e8c1aa-1560049661925)]
1. <%@ page language="java" contentType="text/html; charset=UTF-8"
2. pageEncoding="UTF-8"%>
3. <%@ taglib prefix="s" uri="/struts-tags"%>
4. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
5. <%
6. String path = request.getContextPath();
7. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
8. %>
9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
10. <html xmlns="http://www.w3.org/1999/xhtml">
11. <head>
12. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
13. <title>后台登录</title>
14. </head>
15. <body onload="document.loginForm.j_username.focus();">
16. <!-- 登录表单 -->
17. <form name="loginForm" action="<c:url value='/j_spring_security_check'/>" method="post">
18. <!-- 登录失败后,显示之前的登录名 -->
19. 用户名:<input type='text' name='j_username' class="txtinput"
20. value='<c:if test="${not empty param.login_error}" >
21. <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />
22. <br />
23. 密码:<input type='password' name='j_password' class="txtinput" />
24. <br />
26. <input type="checkbox" name="_spring_security_remember_me" />
27. 保存登录信息
28. <input name="submit" type="submit" value="提交" />
29. <input name="reset" type="reset" value="重置" />
31. </form>
32. <br />
33. <!-- 显示登录失败原因 -->
34. <c:if test="${not empty param.error}">
35. <font color="red"> 登录失败<br />
36. <br />
37. 原因: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />. </font>
38. </c:if>
39. </body>
40. </html>
**5、站点根路径下创建注销页面loggedout.jsp,代码如下:**
Html代码 [图片上传失败...(image-2a8928-1560049661925)]
1. <%@page session="false" %>
2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3. <%@ page pageEncoding="UTF-8"%>
4. <%
5. String path = request.getContextPath();
6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
7. %>
8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
9. <html xmlns="http://www.w3.org/1999/xhtml">
10. <head>
11. <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
12. <title>登出</title>
13. </head>
14. <body>
15. 你已经退出。
16. <a href="<c:url value='/login.jsp'/>">点击这里登录</a>
17. </body>
18. </html>
**6、站点根路径下创建HttpSession超时提示页面timeout.jsp,代码如下:**
Html代码 [图片上传失败...(image-ab481e-1560049661925)]
1. <%@page session="false" %>
2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3. <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
4. <%
5. String path = request.getContextPath();
6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
7. %>
8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
9. <html xmlns="http://www.w3.org/1999/xhtml">
10. <head>
11. <title>用户失效</title>
12. </head>
13. <body>
14. 你的登录已经失效,请重新登录。
15. <br />
16. <a href="<c:url value='/login.jsp'/>" >
17. 点击这里登录</a>
18. </body>
19. </html>
**7、在com.xxx.security包下创建登录验证过滤器,该过滤器可用于在管理员登录时进行日志记录等相关操作,包括两个类:**
* LoginUsernamePasswordAuthenticationFilter
* LoginSuccessHandler
**7.1)LoginUsernamePasswordAuthenticationFilter代码如下:**
Java代码 [图片上传失败...(image-d2a9a6-1560049661925)]
1. package com.xxx.security;
2. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
4. public class LoginUsernamePasswordAuthenticationFilter extends
5. UsernamePasswordAuthenticationFilter {
7. }
**7.2)LoginSuccessHandler代码如下:**
Java代码 [图片上传失败...(image-26cfab-1560049661925)]
1. package com.xxx.security;
3. import java.io.IOException;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import org.springframework.security.core.Authentication;
8. import org.springframework.security.core.userdetails.UserDetails;
9. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
11. /**
12. * 处理管理员登录日志
13. *
14. */
15. public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
17. @Override
18. public void onAuthenticationSuccess(HttpServletRequest request,
19. HttpServletResponse response, Authentication authentication) throws IOException,
20. ServletException {
22. UserDetails userDetails = (UserDetails)authentication.getPrincipal();
24. //输出登录提示信息
25. System.out.println("管理员 " + userDetails.getUsername() + " 登录");
27. super.onAuthenticationSuccess(request, response, authentication);
28. }
30. }
**8、在applicationContext-security.xml中加入权限管理配置,如下:**
Xml代码 [图片上传失败...(image-9c333b-1560049661925)]
1. <?xml version="1.0" encoding="UTF-8"?>
3. <beans:beans xmlns="http://www.springframework.org/schema/security"
4. xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
9. <http >
10. <!-- 不拦截login.jsp -->
11. <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
12. <!--仅拦截到manager下面的内容,具备access对应权限的-->
13. <intercept-url pattern="/manager/**" access="ROLE_ADMIN,ROLE_UPDATE_FILM,ROLE_DELETE_FILM,ROLE_ADD_FILM" />
14. <!-- 设置登录过滤器 -->
15. <custom-filter before="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter" />
16. <!-- 登录表单设置 -->
17. <form-login login-page="/login.jsp"
18. default-target-url="/manager/films.jsp"
19. authentication-failure-url="/login.jsp?error=true" />
21. <!-- 登出操作后跳转到该页面 -->
22. <logout logout-success-url="/loggedout.jsp"
23. delete-cookies="JSESSIONID" />
24. <remember-me />
26. <!-- SESSION超时后跳转到该页面 -->
27. <session-management invalid-session-url="/timeout.jsp">
28. </session-management>
29. </http>
31. <authentication-manager alias="authenticationManager">
32. <authentication-provider>
33. <!--
34. 直接使用SQL语句查询登录帐号对应权限,
35. users-by-username-query:查询登录用户是否存在
36. authorities-by-username-query:查询登录用户权限(登录用户可以不属于任何组,从t_user_role表中获取权限)
37. group-authorities-by-username-query:查询登录用户所在组的权限
38. -->
39. <jdbc-user-service data-source-ref="dataSource"
40. group-authorities-by-username-query="SELECT g.id,g.groupname,role.role
41. FROM t_group AS g
42. LEFT OUTER JOIN t_group_role AS grouprole ON (g.id = grouprole.groupid)
43. LEFT OUTER JOIN t_role AS role ON (role.id = grouprole.roleid)
44. LEFT OUTER JOIN t_group_user AS groupuser on (g.id = groupuser.groupid)
45. LEFT OUTER JOIN t_admin ON (t_admin.id = groupuser.userid)
46. WHERE t_admin.nickname = ?"
47. users-by-username-query="SELECT t_admin.nickname AS username,t_admin.passwd as password,'true' AS enabled
48. FROM t_admin
49. WHERE t_admin.nickname = ?"
50. authorities-by-username-query="SELECT t_admin.nickname AS username,role.role as authorities
51. FROM t_admin
52. LEFT OUTER JOIN t_user_role AS userrole ON(t_admin.id = userrole.userid)
53. LEFT OUTER JOIN t_role AS role ON (userrole.roleid = role.id)
54. WHERE t_admin.nickname = ?" />
55. </authentication-provider>
56. </authentication-manager>
58. <!-- 自定义消息 -->
59. <b:bean id="messageSource"
60. class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
61. <b:property name="basename"
62. value="classpath:org/springframework/security/messages" />
63. </b:bean>
65. <!-- 定制登录过滤器 -->
66. <beans:bean id="loginSuccessHandler" class="com.xxx.security.LoginSuccessHandler">
67. <b:property name="defaultTargetUrl">
68. <!-- 登录成功后转发到该页面 -->
69. <b:value>/manager/films.jsp</b:value>
70. </b:property>
71. </beans:bean>
72. <beans:bean id="authenticationProcessingFilter" class="com.xxx.security.LoginUsernamePasswordAuthenticationFilter">
73. <beans:property name="authenticationSuccessHandler" ref="loginSuccessHandler"></beans:property>
74. <beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"></beans:property>
75. <beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
76. </beans:bean>
77. <beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
78. <beans:property name="defaultFailureUrl">
79. <!-- 登录失败后转发到该页面 -->
80. <beans:value>/login.jsp?error=true</beans:value>
81. </beans:property>
82. </beans:bean>
84. </beans:beans>
注:
<pre id="best-content-2655932032" style="box-sizing: border-box; outline: 0px; margin: 0px 0px 24px; padding: 8px; position: relative; font-family: Consolas, Inconsolata, Courier, monospace; white-space: pre-wrap; overflow-wrap: break-word; overflow-x: auto; font-size: 14px; line-height: 22px; color: rgb(0, 0, 0); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">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,在认证过滤器中使用
</pre>
9、为影片页面films.jsp定制操作权限,定制后,不同的帐号登录会看到不同的操作,
比如,帐号"admin"属于权限组"Administrator",具备权限"ROLE_ADMIN",登录后
可以看到所有操作,帐号"test"属于权限组"影片维护",具备权限"ROLE_UPDATE_FILM"
和"ROLE_ADD_FILM",登录后只能看到"添加影片信息"和"修改"操作
films.jsp页面权限分布图:
[图片上传失败...(image-c45b3b-1560049661927)]
films.jsp代码如下:
Html代码 [图片上传失败...(image-4fe400-1560049661925)]
1. <%@ page language="java" contentType="text/html; charset=utf-8"
2. pageEncoding="utf-8" %>
3. <%@taglib uri="/struts-tags" prefix="s" %>
4. <%@ taglib prefix="security"
5. uri="http://www.springframework.org/security/tags"%>
6. <%
7. String path = request.getContextPath();
8. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
9. %>
10. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11. <html>
12. <head>
13. <title>信息操作</title>
14. </head>
15. <body>
16. <s:form action="/film/findFilm" method="post">
17. <s:submit value=" 获取所有影片信息 "></s:submit>
18. </s:form>
19. <!-- 添加影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_ADD_FILM权限可以执行 -->
20. <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_ADD_FILM">
21. <a href="<%=basePath %>manager/insertFilm.jsp">添加影片信息</a><br />
22. </security:authorize>
24. <s:if test="filmList != null">
25. <table border="1" width="40%">
26. <tr>
27. <th>序号</th><th>影片名</th><th>操作</th>
28. </tr>
29. <%-- 遍历影片信息 --%>
30. <s:iterator var="film" value="filmList" status="st">
31. <tr>
32. <td><s:property value="#st.index+1" /></td>
33. <td><s:property value="fname" /></td>
34. <td>
36. <!-- 修改影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_UPDATE_FILM权限可以执行 -->
37. <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_UPDATE_FILM">
38. <s:url id="detailUrl" value="/film/detailFilm">
39. <s:param name="id" value="%{id}"/>
40. </s:url>
41. <s:a href="%{detailUrl}">[修改]</s:a>
42. </security:authorize>
43. <!-- 删除影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_DELETE_FILM权限可以执行 -->
44. <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_DELETE_FILM">
45. <s:url id="deleteUrl" value="/film/deleteFilm">
46. <s:param name="id" value="%{id}"/>
47. </s:url>
48. <s:a href="%{deleteUrl}">[删除]</s:a>
49. </security:authorize>
50. </td>
51. </tr>
52. </s:iterator>
53. </table>
54. </s:if>
55. </body>
56. </html>
Shrio在线教程:
http://www.sojson.com/jc/shiro.html
Shiro + Redis 源码