springboot---整合shiro
生活随笔
收集整理的這篇文章主要介紹了
springboot---整合shiro
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Shiro是一個非常不錯的權限框架,它提供了登錄和權限驗證功能
1.創建數據庫腳本
當新添加一個用戶時,只需要配置權限即可,module_role表中已經配置了什么權限擁有什么樣的功能
SELECT u.*,r.*,m.* FROM user u inner join user_role ur on ur.uid=u.uidinner join role r on r.rid=ur.ridinner join module_role mr on mr.rid=r.ridinner join module m on mr.mid=m.midWHERE username='hlhdidi'; -- xyycici用戶已分配只要兩個權限 add和query2.pom.xml中添加Springboot集成shiro的相關依賴
<!-- shiro整合springboot所需相關依賴--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.2.5</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.5</version></dependency><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>1.2.1</version></dependency> <!--end.......-->3.創建實體類
僅列出關鍵實體類,其他實體類無需改動
用戶
package com.king.s5.model;import java.io.Serializable; import java.util.HashSet; import java.util.Set; //用戶 public class User implements Serializable{private Integer uid;private String username;private String password;private Set<Role> roles = new HashSet<>();public User(Integer uid, String username, String password) {this.uid = uid;this.username = username;this.password = password;}public User() {super();}public Integer getUid() {return uid;}public void setUid(Integer uid) {this.uid = uid;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Set<Role> getRoles() {return roles;}public void setRoles(Set<Role> roles) {this.roles = roles;} }功能
package com.king.s5.model;import java.util.HashSet; import java.util.Set; //功能 public class Module {private Integer mid;private String mname;private Set<Role> roles;public Module(Integer mid, String mname) {this.mid = mid;this.mname = mname;}public Module() {super();}public Integer getMid() {return mid;}public void setMid(Integer mid) {this.mid = mid;}public String getMname() {return mname;}public void setMname(String mname) {this.mname = mname;}public Set<Role> getRoles() {return roles;}public void setRoles(Set<Role> roles) {this.roles = roles;} }權限
public class Role {private Integer rid;private String rname;private Set<User> users = new HashSet<>();private Set<Module> Modules = new HashSet<>();public Role(Integer rid, String rname) {this.rid = rid;this.rname = rname;}public Role() {super();}public Integer getRid() {return rid;}public void setRid(Integer rid) {this.rid = rid;}public String getRname() {return rname;}public void setRname(String rname) {this.rname = rname;}public Set<User> getUsers() {return users;}public void setUsers(Set<User> users) {this.users = users;}public Set<Module> getModules() {return Modules;}public void setModules(Set<Module> modules) {Modules = modules;} }4.編寫持久層mapper.xml
userMapper.xml,本次只寫到mapper層,不做service層(僅列出關鍵mapper.xml),其他xml無需改變
moduleMapper.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.king.s5.mapper.ModuleMapper" ><resultMap id="BaseResultMap" type="com.king.s5.model.Module" ><constructor ><idArg column="mid" jdbcType="INTEGER" javaType="java.lang.Integer" /><arg column="mname" jdbcType="VARCHAR" javaType="java.lang.String" /></constructor></resultMap><sql id="Base_Column_List" >mid, mname</sql><select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from modulewhere mid = #{mid,jdbcType=INTEGER}</select><delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >delete from modulewhere mid = #{mid,jdbcType=INTEGER}</delete><insert id="insert" parameterType="com.king.s5.model.Module" >insert into module (mid, mname)values (#{mid,jdbcType=INTEGER}, #{mname,jdbcType=VARCHAR})</insert><insert id="insertSelective" parameterType="com.king.s5.model.Module" >insert into module<trim prefix="(" suffix=")" suffixOverrides="," ><if test="mid != null" >mid,</if><if test="mname != null" >mname,</if></trim><trim prefix="values (" suffix=")" suffixOverrides="," ><if test="mid != null" >#{mid,jdbcType=INTEGER},</if><if test="mname != null" >#{mname,jdbcType=VARCHAR},</if></trim></insert><update id="updateByPrimaryKeySelective" parameterType="com.king.s5.model.Module" >update module<set ><if test="mname != null" >mname = #{mname,jdbcType=VARCHAR},</if></set>where mid = #{mid,jdbcType=INTEGER}</update><update id="updateByPrimaryKey" parameterType="com.king.s5.model.Module" >update moduleset mname = #{mname,jdbcType=VARCHAR}where mid = #{mid,jdbcType=INTEGER}</update> </mapper>5.添加shiro的工具類
認證授權工具類
權限用戶密碼校驗類
package com.king.s5.shiro;import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;public class CredentialsMatcher extends SimpleCredentialsMatcher {//校驗@Overridepublic boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {UsernamePasswordToken utoken=(UsernamePasswordToken) token;//獲得用戶輸入的密碼:(可以采用加鹽(salt)的方式去檢驗)String inPassword = new String(utoken.getPassword());//獲得數據庫中的密碼String dbPassword=(String) info.getCredentials();//進行密碼的比對return this.equals(inPassword, dbPassword);} }shiro配置類
package com.king.s5.shiro;import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.mgt.SecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import java.util.LinkedHashMap;/*** shiro的配置類* @author sujin**/ @Configuration public class ShiroConfiguration {@Bean(name="shiroFilter")public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();bean.setSecurityManager(manager);//配置登錄的url和登錄成功的urlbean.setLoginUrl("/login");bean.setSuccessUrl("/home");//配置訪問權限LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();filterChainDefinitionMap.put("/login*", "anon"); //表示可以匿名訪問filterChainDefinitionMap.put("/loginUser", "anon");filterChainDefinitionMap.put("/client/test", "anon");filterChainDefinitionMap.put("/assert/test", "anon");//添加白名單filterChainDefinitionMap.put("/assert/get", "anon");//添加白名單filterChainDefinitionMap.put("/assert/assertQuery", "anon");//添加白名單filterChainDefinitionMap.put("/a", "anon");filterChainDefinitionMap.put("/book/list", "anon");filterChainDefinitionMap.put("/logout*","anon");filterChainDefinitionMap.put("/jsp/error.jsp*","anon");filterChainDefinitionMap.put("/jsp/login.jsp*","authc");filterChainDefinitionMap.put("/*", "authc");//表示需要認證才可以訪問filterChainDefinitionMap.put("/**", "authc");//表示需要認證才可以訪問filterChainDefinitionMap.put("/*.*", "authc");bean.setFilterChainDefinitionMap(filterChainDefinitionMap);return bean;}//配置核心安全事務管理器@Bean(name="securityManager")public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) {System.err.println("--------------shiro已經加載----------------");DefaultWebSecurityManager manager=new DefaultWebSecurityManager();manager.setRealm(authRealm);return manager;}//配置自定義的權限登錄器@Bean(name="authRealm")public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {AuthRealm authRealm=new AuthRealm();authRealm.setCredentialsMatcher(matcher);return authRealm;}//配置自定義的密碼比較器@Bean(name="credentialsMatcher")public CredentialsMatcher credentialsMatcher() {return new CredentialsMatcher();}@Beanpublic LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){return new LifecycleBeanPostProcessor();}@Beanpublic DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator();creator.setProxyTargetClass(true);return creator;}@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();advisor.setSecurityManager(manager);return advisor;} }6.控制層controller
package com.king.s5.controller;import com.king.s5.model.User; 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.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpSession;@Controller public class LoginController {@RequestMapping("/login")public String login() {return "login";}@RequestMapping("/a")public String a() {return "a";}@RequestMapping("/loginUser")public String loginUser(String username,String password,HttpSession session) {//授權認證UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);Subject subject = SecurityUtils.getSubject();try {//完成登錄subject.login(usernamePasswordToken);//獲得用戶對象User user=(User) subject.getPrincipal();//存入sessionsession.setAttribute("user", user);return "index";} catch(Exception e) {return "login";//返回登錄頁面}}@RequestMapping("/logOut")public String logOut(HttpSession session) {Subject subject = SecurityUtils.getSubject();subject.logout(); // session.removeAttribute("user");return "login";} }7.視圖層jsp
login.jsp
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> <!DOCTYPE html> <html lang="en"> <head><title>登錄</title> </head><h1>歡迎${user.username }光臨!請選擇你的操作:</h1><br> <ul><shiro:hasPermission name="add"><li>增加</li></shiro:hasPermission><shiro:hasPermission name="delete"><li>刪除</li></shiro:hasPermission><shiro:hasPermission name="update"><li>修改</li></shiro:hasPermission><shiro:hasPermission name="query"><li>查詢</li></shiro:hasPermission></ul> <a href="${pageContext.request.contextPath }/logOut">點我注銷</a> </body> </html>8.shiro標簽的使用
| user標簽 | 認證通過或已記住的用戶 |
| authenticated標簽 | 已認證通過的用戶。不包含已記住的用戶,這是與user標簽的區別所在未認證通過用戶,與authenticated標簽相對應。與guest標簽的區別是,該標簽包含已記住用戶 |
| notAuthenticated標簽 | |
| principal 標簽 | 輸出當前用戶信息,通常為登錄帳號信息 |
| hasRole標簽 | 驗證當前用戶是否屬于該角色 |
| lacksRole標簽 | 與hasRole標簽邏輯相反,當用戶不屬于該角色時驗證通過 |
| hasAnyRole標簽 | 驗證當前用戶是否屬于以下任意一個角色 |
| hasPermission標簽 | 驗證當前用戶是否擁有指定權限 |
| lacksPermission標簽 | 與hasPermission標簽邏輯相反,當前用戶沒有制定權限時,驗證通過 |
總結
以上是生活随笔為你收集整理的springboot---整合shiro的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dataoutputstream.wri
- 下一篇: Shiro表结构设计