springMVC整合shiro

y534560449發表於2016-12-19

shiro是什麼:Apache Shiro是一個強大易用的Java安全框架,提供了認證、授權、加密和會話管理功能,可為任何應用提供安全保障。

shiro官方文件:http://shiro.apache.org/authentication.html。

首先在pom.xml中新增shiro依賴:

<!-- shiro核心包 -->
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-core</artifactId>
	<version>1.2.5</version>
</dependency>
<!-- 新增shiro web支援 -->
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-web</artifactId>
	<version>1.2.5</version>
</dependency>
<!-- 新增shiro spring支援 -->
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-spring</artifactId>
	<version>1.2.5</version>
</dependency>
<!-- 新增jstl支援 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>
編寫自己的Realm(當驗證currentUser.login(token)時會執行此類的方法):

package com.yrok.realm;

import javax.annotation.Resource;

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.yrok.entity.TUser;
import com.yrok.mapper.UserMapper;

public class MyRealm extends AuthorizingRealm {

	@Resource
	UserMapper userMapper;
	/**
	 * 為當前已經登陸成功的使用者授予許可權和角色
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal(); // 獲取使用者名稱
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(userMapper.getRoles(username)); //設定角色
        authorizationInfo.setStringPermissions(userMapper.getPermissions(username)); //設定許可權            
		return authorizationInfo;
	}

	/**
	 * 驗證當前正在登入的使用者,獲取認證資訊
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal(); // 獲取使用者名稱
		TUser tUser = userMapper.getByUsername(username);
		 if (tUser != null) {
             AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(tUser.getUsername(), tUser.getPassword(), "myrealm");
             return authcInfo;
         } else {
             return null;
         }
	}

}
spring整合mybatis參考我的另一篇文章:SSM配置模板

編寫UserMapper:

package com.yrok.mapper;

import java.util.List;
import java.util.Set;

import org.apache.ibatis.annotations.Param;

import com.yrok.entity.TUser;


public interface UserMapper {
	
	public TUser getByUsername(String username);

	public Set<String> getRoles(String username);

	public Set<String> getPermissions(String username);

}

編寫UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yrok.mapper.UserMapper" >
 
   <select id="getByUsername" parameterType="String" resultType="TUser">
        select * from t_user where username=#{username}
    </select>

    <select id="getRoles" parameterType="String" resultType="String">
        select r.rolename from t_user u,t_role r where u.role_id=r.id and u.username=#{username}
    </select>

    <select id="getPermissions" parameterType="String" resultType="String">
        select p.permissionname from t_user u,t_role r,t_permission p where u.role_id=r.id and p.role_id=r.id and u.username=#{username}
    </select>
</mapper>


編寫UserController:

package com.yrok.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yrok.entity.TUser;
import com.yrok.entity.User;
import com.yrok.service.UserService;
@Controller
@RequestMapping(value="/user")
public class UserController {

	@Resource
	UserService userService;

	//使用者登入
    @RequestMapping("/login")
    public String login(TUser user, HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try{
            subject.login(token);//會跳到我們自定義的realm中
            request.getSession().setAttribute("username", user.getUsername());
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("username", user.getUsername());
            request.setAttribute("error", "使用者名稱或密碼錯誤!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
        return null;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return null;
    }   

    @RequestMapping("/admin")
    public String admin(HttpServletRequest request) {
        return "success";
    }

    @RequestMapping("/student")
    public String student(HttpServletRequest request) {
        return "success";
    }   

    @RequestMapping("/teacher")
    public String teacher(HttpServletRequest request) {
        return "success";
    }   
	
}


最後spring整合shiro的配置:

<!-- 自定義Realm -->
<bean id="myRealm" class="com.yrok.realm.MyRealm"/>  
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  <property name="realm" ref="myRealm"/>  
</bean>  

<!-- Shiro過濾器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
	<!-- Shiro的核心安全介面,這個屬性是必須的 -->  
	<property name="securityManager" ref="securityManager"/>
	<!-- 身份認證失敗,則跳轉到登入頁面的配置 -->  
	<property name="loginUrl" value="/login.jsp"/>
	<!-- 許可權認證失敗,則跳轉到指定頁面 -->  
	<property name="unauthorizedUrl" value="/unauthorized.jsp"/>  
	<!-- Shiro連線約束配置,即過濾鏈的定義 -->  
	<property name="filterChainDefinitions">  
		<value>  
			<!-- 訪問login是不需要認證 -->
			/login=anon 
			<!-- 訪問user/admin開頭的任意介面都需要認證 -->
			/user/admin*=authc
			/user/student*/**=roles[teacher]
			/user/teacher*/**=perms["user:create"]
		</value>  
	</property>
</bean>  

<!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->  
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  

<!-- 開啟Shiro註解 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>  
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  <property name="securityManager" ref="securityManager"/>  
</bean>  

資料庫sql:

CREATE TABLE `t_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `rolename` varchar(20) DEFAULT NULL COMMENT '角色名稱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '使用者主鍵',
  `username` varchar(20) NOT NULL COMMENT '使用者名稱',
  `password` varchar(20) NOT NULL COMMENT '密碼',
  `role_id` int(11) DEFAULT NULL COMMENT '外來鍵關聯role表',
  PRIMARY KEY (`id`),
  KEY `role_id` (`role_id`),
  CONSTRAINT `t_user_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

CREATE TABLE `t_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `permissionname` varchar(50) NOT NULL COMMENT '許可權名',
  `role_id` int(11) DEFAULT NULL COMMENT '外來鍵關聯role',
  PRIMARY KEY (`id`),
  KEY `role_id` (`role_id`),
  CONSTRAINT `t_permission_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
測試:

根據spring的配置檔案中對shiro的url攔截配置,我們首先請求:http://localhost:8080/SSMShiro/user/admin來測試身份認證,然後會跳轉到登入頁面讓我們登陸,登陸成功後,再次請求這個url就會進入success.jsp頁面了。
再測試角色和許可權認證,可以先後輸入http://localhost:8080/ShiroSpring/user/student來測試角色認證,輸入http://localhost:8080/SSMShiro/user/teacher來測試許可權認證。通過登陸不同的使用者去測試即可。
參考文件:

【Shiro】Apache Shiro架構之許可權認證(Authorization)
【Shiro】Apache Shiro架構之整合web
【Shiro】Apache Shiro架構之自定義realm
【Shiro】Apache Shiro架構之實際運用(整合到Spring中)

相關文章