博文目錄
- 權限的簡單描述
- 實例表結構及內容及POJO
- Shiro-pom.xml
- Shiro-web.xml
- Shiro-MyShiro-權限認證,登陸認證層
- Shiro-applicationContext-shiro.xml
- HomeController
- 三個JSP文件
什麼是權限呢?舉個簡單的例子:
我有一個論壇,註冊的用戶分爲normal用戶,manager用戶。
對論壇的帖子的操做有這些:
添加,刪除,更新,查看,回覆
咱們規定:
normal用戶只能:添加,查看,回覆
manager用戶能夠:刪除,更新
normal,manager對應的是角色(role)
添加,刪除,更新等對應的是權限(permission)
咱們採用下面的邏輯建立權限表結構(不是絕對的,根據須要修改)
一個用戶能夠有多種角色(normal,manager,admin等等)
一個角色能夠有多個用戶(user1,user2,user3等等)
一個角色能夠有多個權限(save,update,delete,query等等)
一個權限只屬於一個角色(delete只屬於manager角色)javascript
咱們建立四張表:
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
-----------------------------------css
創建對應的POJO:html
- 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
- @Table(name="t_user")
- 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(){
- List<Role> roles=getRoleList();
- Set<String> set=new HashSet<String>();
- for (Role role : roles) {
- set.add(role.getRolename());
- }
- 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
- @Table(name="t_role")
- 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(){
- List<String> list=new ArrayList<String>();
- List<Permission> perlist=getPermissionList();
- for (Permission per : perlist) {
- list.add(per.getPermissionname());
- }
- 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
- @Table(name="t_permission")
- 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中配置以下:java
web.xml中的配置:mysql
- <?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
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Archetype Created Web Application</display-name>
-
-
- <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>
-
-
- <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>
-
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
-
-
- <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
- @Transactional
- public class MyShiro extends AuthorizingRealm{
-
- @Inject
- private UserService userService;
-
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
-
- String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();
-
- User user=userService.findByName(loginName);
- if(user!=null){
-
- SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
-
- info.setRoles(user.getRolesName());
-
- List<Role> roleList=user.getRoleList();
- for (Role role : roleList) {
- info.addStringPermissions(role.getPermissionsName());
- }
- return info;
- }
- return null;
- }
-
-
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(
- AuthenticationToken authenticationToken) throws AuthenticationException {
-
- UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
-
- User user=userService.findByName(token.getUsername());
- if(user!=null){
-
- return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
- }
- return null;
- }
-
- }
在spring的配置文件中配置,爲了區別spring原配置和shiro咱們將shiro的配置獨立出來。jquery
applicationContext-shiro.xmlweb
- <?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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">
-
- <property name="realm" ref="myShiro"/>
-
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager"/>
-
- <property name="loginUrl" value="/login"/>
-
- <property name="successUrl" value="/user"/>
-
- <property name="unauthorizedUrl" value="/403"/>
-
- <property name="filterChainDefinitions">
- <value>
-
- /static/**=anon
-
- /user=perms[user:query]
-
- /user/add=roles[manager]
- /user/del/**=roles[admin]
- /user/edit/**=roles[manager]
-
- /** = authc
- </value>
- </property>
- </bean>
-
-
- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
-
- </beans>
用於登陸,登出,權限跳轉的控制:ajax
- 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){
- model.addAttribute("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";
- }
-
- SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
- return "redirect:/user";
- } catch (AuthenticationException e) {
- redirectAttributes.addFlashAttribute("message","用戶名或密碼錯誤");
- return "redirect:/login";
- }
- }
-
- @RequestMapping(value="/logout",method=RequestMethod.GET)
- public String logout(RedirectAttributes redirectAttributes ){
-
- SecurityUtils.getSubject().logout();
- redirectAttributes.addFlashAttribute("message", "您已安全退出");
- return "redirect:/login";
- }
-
- @RequestMapping("/403")
- public String unauthorizedRole(){
- return "/403";
- }
- }
三個主要的JSP:
login.jsp:spring
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <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:sql
- <%@ 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" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <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>
- $(function(){
- $(".del").click(function(){
- var id=$(this).attr("ref");
- $.ajax({
- type:"delete",
- url:"/user/del/"+id,
- success:function(e){
-
- }
- });
- });
- });
- </script>
- </body>
- </html>
403.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>權限錯誤</title>
- </head>
-
- <body>
- <h1>對不起,您沒有權限請求此鏈接!</h1>
- <img alt="" src="/static/img/1.jpg">
-
- </body>
- </html>