实现对特定角色和特定路径拦截

This commit is contained in:
fjy8018@qq.com
2018-07-06 15:44:45 +08:00
parent 14bdaf5989
commit 0be0ccf113
11 changed files with 226 additions and 173 deletions

184
pom.xml
View File

@@ -1,111 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>top.fjy8018</groupId> <groupId>top.fjy8018</groupId>
<artifactId>shiro</artifactId> <artifactId>shiro</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>shiro</name> <name>shiro</name>
<description>Demo project for Spring Boot plus Shiro</description> <description>Demo project for Spring Boot plus Shiro</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version> <version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version> <version>1.3.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core --> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId> <artifactId>shiro-core</artifactId>
<version>1.4.0</version> <version>1.4.0</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring --> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId> <artifactId>shiro-spring</artifactId>
<version>1.4.0</version> <version>1.4.0</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid</artifactId> <artifactId>druid</artifactId>
<version>1.1.10</version> <version>1.1.10</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.7</version> <version>3.7</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId> <artifactId>spring-context-support</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper --> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency> <dependency>
<groupId>org.apache.tomcat</groupId> <groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId> <artifactId>tomcat-jasper</artifactId>
<version>9.0.10</version> <version>9.0.10</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId> <artifactId>javax.servlet-api</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl --> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId> <artifactId>jstl</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

92
sql.sql
View File

@@ -1,30 +1,39 @@
DROP DATABASE db_shiroTest; DROP DATABASE db_shiroTest;
GRANT ALL ON db_shiroTest.* TO trs@localhost IDENTIFIED BY 'shiro'; GRANT ALL ON db_shiroTest.* TO trs@localhost
flush privileges; IDENTIFIED BY 'shiro';
CREATE DATABASE IF NOT EXISTS db_shiroTest DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci; FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS db_shiroTest
DEFAULT CHARSET utf8mb4
COLLATE utf8mb4_general_ci;
USE db_shiroTest; USE db_shiroTest;
-- 权限表 -- -- 权限表 --
CREATE TABLE permission ( CREATE TABLE permission (
pid INT(11) NOT NULL AUTO_INCREMENT, pid INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL DEFAULT '', name VARCHAR(255) NOT NULL DEFAULT '',
url VARCHAR(255) DEFAULT '', url VARCHAR(255) DEFAULT '',
PRIMARY KEY (pid) PRIMARY KEY (pid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; )
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 用户表 -- -- 用户表 --
CREATE TABLE user ( CREATE TABLE user (
uid INT(11) NOT NULL AUTO_INCREMENT, uid INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL DEFAULT '', username VARCHAR(255) NOT NULL DEFAULT '',
password VARCHAR(255) NOT NULL DEFAULT '', password VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (uid) PRIMARY KEY (uid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; )
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 角色表 -- -- 角色表 --
CREATE TABLE role ( CREATE TABLE role (
rid INT(11) NOT NULL AUTO_INCREMENT, rid INT(11) NOT NULL AUTO_INCREMENT,
rname VARCHAR(255) NOT NULL DEFAULT '', rname VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (rid) PRIMARY KEY (rid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; )
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 权限角色关系表 -- -- 权限角色关系表 --
CREATE TABLE permission_role ( CREATE TABLE permission_role (
@@ -32,7 +41,9 @@ CREATE TABLE permission_role (
pid INT(11) NOT NULL, pid INT(11) NOT NULL,
CONSTRAINT FK_prid FOREIGN KEY (rid) REFERENCES role (rid), CONSTRAINT FK_prid FOREIGN KEY (rid) REFERENCES role (rid),
CONSTRAINT FK_pid FOREIGN KEY (pid) REFERENCES permission (pid) CONSTRAINT FK_pid FOREIGN KEY (pid) REFERENCES permission (pid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; )
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 用户角色关系表 -- -- 用户角色关系表 --
CREATE TABLE user_role ( CREATE TABLE user_role (
@@ -40,38 +51,43 @@ CREATE TABLE user_role (
uid INT(11) NOT NULL, uid INT(11) NOT NULL,
CONSTRAINT FK_urid FOREIGN KEY (rid) REFERENCES role (rid), CONSTRAINT FK_urid FOREIGN KEY (rid) REFERENCES role (rid),
CONSTRAINT FK_uid FOREIGN KEY (uid) REFERENCES user (uid) CONSTRAINT FK_uid FOREIGN KEY (uid) REFERENCES user (uid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; )
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 初始化数据 -- -- 初始化数据 --
INSERT INTO permission (pid,name, url) VALUE ('1','add',''); INSERT INTO permission (pid, name, url) VALUE ('1', 'add', '');
INSERT INTO permission (pid,name, url) VALUE ('2','delete',''); INSERT INTO permission (pid, name, url) VALUE ('2', 'delete', '');
INSERT INTO permission (pid,name, url) VALUE ('3','edit',''); INSERT INTO permission (pid, name, url) VALUE ('3', 'edit', '');
INSERT INTO permission (pid,name, url) VALUE ('4','query',''); INSERT INTO permission (pid, name, url) VALUE ('4', 'query', '');
INSERT INTO user (uid,username, password) VALUE ('1','admin','0000'); INSERT INTO user (uid, username, password) VALUE ('1', 'admin', '0000');
INSERT INTO user (uid,username, password) VALUE ('2','trs','trs'); INSERT INTO user (uid, username, password) VALUE ('2', 'trs', 'trs');
INSERT INTO role (rid,rname) VALUE ('1','admin'); INSERT INTO role (rid, rname) VALUE ('1', 'admin');
INSERT INTO role (rid,rname) VALUE ('2','customer'); INSERT INTO role (rid, rname) VALUE ('2', 'customer');
INSERT INTO role (rid,rname) VALUE ('3','guest'); INSERT INTO role (rid, rname) VALUE ('3', 'guest');
INSERT INTO permission_role (rid, pid) VALUE ('1','1'); INSERT INTO permission_role (rid, pid) VALUE ('1', '1');
INSERT INTO permission_role (rid, pid) VALUE ('1','2'); INSERT INTO permission_role (rid, pid) VALUE ('1', '2');
INSERT INTO permission_role (rid, pid) VALUE ('1','3'); INSERT INTO permission_role (rid, pid) VALUE ('1', '3');
INSERT INTO permission_role (rid, pid) VALUE ('1','4'); INSERT INTO permission_role (rid, pid) VALUE ('1', '4');
INSERT INTO permission_role (rid, pid) VALUE ('2','1'); INSERT INTO permission_role (rid, pid) VALUE ('2', '1');
INSERT INTO permission_role (rid, pid) VALUE ('1','3'); INSERT INTO permission_role (rid, pid) VALUE ('1', '3');
INSERT INTO permission_role (rid, pid) VALUE ('1','4'); INSERT INTO permission_role (rid, pid) VALUE ('1', '4');
INSERT INTO permission_role (rid, pid) VALUE ('3','4'); INSERT INTO permission_role (rid, pid) VALUE ('3', '4');
INSERT INTO user_role (rid, uid) VALUE ('1','1'); INSERT INTO user_role (rid, uid) VALUE ('1', '1');
INSERT INTO user_role (rid, uid) VALUE ('2','2'); INSERT INTO user_role (rid, uid) VALUE ('2', '2');
SELECT u.*,r.*,p.* SELECT
FROM user u u.*,
INNER JOIN user_role ur ON ur.uid = u.uid r.*,
INNER JOIN role r ON ur.uid = r.rid p.*
INNER JOIN permission_role pr ON r.rid = pr.rid FROM user u
INNER JOIN permission p ON pr.pid = p.pid INNER JOIN user_role ur ON ur.uid = u.uid
WHERE u.username INNER JOIN role r ON ur.uid = r.rid
INNER JOIN permission_role pr ON r.rid = pr.rid
INNER JOIN permission p ON pr.pid = p.pid
WHERE u.username

View File

@@ -10,7 +10,7 @@ import org.springframework.context.annotation.ComponentScan;
@MapperScan(basePackages = {"top.fjy8018.shiro.mapper"}) @MapperScan(basePackages = {"top.fjy8018.shiro.mapper"})
public class ShiroApplication { public class ShiroApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ShiroApplication.class, args); SpringApplication.run(ShiroApplication.class, args);
} }
} }

View File

@@ -15,6 +15,7 @@ import java.util.LinkedHashMap;
/** /**
* shiro核心配置 * shiro核心配置
*
* @author F嘉阳 * @author F嘉阳
* @date 2018/7/6 10:29 * @date 2018/7/6 10:29
*/ */
@@ -22,7 +23,7 @@ import java.util.LinkedHashMap;
public class ShiroConfiguration { public class ShiroConfiguration {
@Bean("shiroFilter") @Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager){ public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(manager); bean.setSecurityManager(manager);
@@ -32,11 +33,18 @@ public class ShiroConfiguration {
bean.setUnauthorizedUrl("/unauthorized"); bean.setUnauthorizedUrl("/unauthorized");
// 配置拦截 // 配置拦截
LinkedHashMap<String,String> filterChainDefinitionMap = new LinkedHashMap<>(); LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 主页设置拦截第二个参数的含义在org.apache.shiro.web.filter.mgt.DefaultFilter的枚举类中authc为表单验证 // 主页设置拦截第二个参数的含义在org.apache.shiro.web.filter.mgt.DefaultFilter的枚举类中authc为表单验证
filterChainDefinitionMap.put("/index","authc"); filterChainDefinitionMap.put("/index", "authc");
// 登录页无需拦截anon即匿名访问 // 登录页无需拦截anon即匿名访问
filterChainDefinitionMap.put("/login","anon"); filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/doLogin","anon");
// 指定页面只能给指定用户访问校验角色名称类org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
filterChainDefinitionMap.put("/admin","roles[admin]");
// 用户登录后可以访问所有接口
filterChainDefinitionMap.put("/**", "user");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap); bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
@@ -45,7 +53,7 @@ public class ShiroConfiguration {
@Bean("securityManager") @Bean("securityManager")
public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm){ public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) {
DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(authRealm); manager.setRealm(authRealm);
return manager; return manager;
@@ -54,11 +62,12 @@ public class ShiroConfiguration {
/** /**
* 自定义的Realm * 自定义的Realm
*
* @param matcher * @param matcher
* @return * @return
*/ */
@Bean("authRealm") @Bean("authRealm")
public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher){ public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
AuthRealm authRealm = new AuthRealm(); AuthRealm authRealm = new AuthRealm();
authRealm.setCredentialsMatcher(matcher); authRealm.setCredentialsMatcher(matcher);
return authRealm; return authRealm;
@@ -66,20 +75,22 @@ public class ShiroConfiguration {
/** /**
* 自定义密码校验规则 * 自定义密码校验规则
*
* @return * @return
*/ */
@Bean("credentialsMatcher") @Bean("credentialsMatcher")
public CredentialsMatcher credentialsMatcher(){ public CredentialsMatcher credentialsMatcher() {
return new CredentialsMatcher(); return new CredentialsMatcher();
} }
/** /**
* 配置spring与shiro关联指定spring使用的SecurityManager为自定义的SecurityManager * 配置spring与shiro关联指定spring使用的SecurityManager为自定义的SecurityManager
*
* @param securityManager * @param securityManager
* @return * @return
*/ */
@Bean @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager){ public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager); advisor.setSecurityManager(securityManager);
@@ -88,10 +99,11 @@ public class ShiroConfiguration {
/** /**
* 代理所有servlet的过滤器链 * 代理所有servlet的过滤器链
*
* @return * @return
*/ */
@Bean @Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){ public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true); creator.setProxyTargetClass(true);

View File

@@ -19,25 +19,34 @@ import javax.servlet.http.HttpSession;
public class LoginController { public class LoginController {
@RequestMapping("/login") @RequestMapping("/login")
public String login(){ public String login() {
return "login"; return "login";
} }
@RequestMapping("/doLogin") @RequestMapping("/doLogin")
public String doLogin(LoginForm form, HttpSession session){ public String doLogin(LoginForm form, HttpSession session) {
UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(),form.getPassword()); UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
try{ try {
subject.login(token); subject.login(token);
// 若未发生异常则此处获得用户 // 若未发生异常则此处获得用户
User user = (User) subject.getPrincipal(); User user = (User) subject.getPrincipal();
// 将用户写入session // 将用户写入session
session.setAttribute(GlobalConstant.USER_SESSION_KEY,user); session.setAttribute(GlobalConstant.USER_SESSION_KEY, user);
return "index"; return "index";
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return "login"; return "login";
} }
} }
@RequestMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
subject.logout();
}
return "login";
}
} }

View File

@@ -2,9 +2,11 @@ package top.fjy8018.shiro.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/** /**
* 页面导航 * 页面导航
*
* @author F嘉阳 * @author F嘉阳
* @date 2018/7/6 10:57 * @date 2018/7/6 10:57
*/ */
@@ -12,7 +14,14 @@ import org.springframework.web.bind.annotation.RequestMapping;
public class NavController { public class NavController {
@RequestMapping("/index") @RequestMapping("/index")
public String index(){ public String index() {
return "index"; return "index";
} }
@RequestMapping("/admin")
@ResponseBody
public String admin() {
return "admin success";
}
} }

View File

@@ -7,6 +7,7 @@ import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
/** /**
* 自定义校验规则 * 自定义校验规则
*
* @author F嘉阳 * @author F嘉阳
* @date 2018/7/6 10:25 * @date 2018/7/6 10:25
*/ */
@@ -15,9 +16,9 @@ public class CredentialsMatcher extends SimpleCredentialsMatcher {
@Override @Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String password = new String (usernamePasswordToken.getPassword()); String password = new String(usernamePasswordToken.getPassword());
String dbPassword = (String) info.getCredentials(); String dbPassword = (String) info.getCredentials();
// 数据库密码与用户密码匹配 // 数据库密码与用户密码匹配
return this.equals(password,dbPassword); return this.equals(password, dbPassword);
} }
} }

View File

@@ -4,6 +4,7 @@ import lombok.Data;
/** /**
* 登录表单 * 登录表单
*
* @author F嘉阳 * @author F嘉阳
* @date 2018/7/6 10:59 * @date 2018/7/6 10:59
*/ */

View File

@@ -27,6 +27,7 @@ public class AuthRealm extends AuthorizingRealm {
/** /**
* shiro登录成功后的授权方法 * shiro登录成功后的授权方法
*
* @param principalCollection * @param principalCollection
* @return * @return
*/ */
@@ -36,14 +37,16 @@ public class AuthRealm extends AuthorizingRealm {
User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next(); User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
List<String> permissionList = new ArrayList<>(); List<String> permissionList = new ArrayList<>();
List<String> roleList = new ArrayList<>();
Set<Role> roleSet = user.getRoles(); Set<Role> roleSet = user.getRoles();
// 取角色 // 取角色
if (CollectionUtils.isNotEmpty(roleSet)){ if (CollectionUtils.isNotEmpty(roleSet)) {
for (Role role : roleSet){ for (Role role : roleSet) {
roleList.add(role.getRname());
// 取权限 // 取权限
Set<Permission> permissionSet = role.getPermissions(); Set<Permission> permissionSet = role.getPermissions();
if (CollectionUtils.isNotEmpty(permissionSet)){ if (CollectionUtils.isNotEmpty(permissionSet)) {
for (Permission permission : permissionSet){ for (Permission permission : permissionSet) {
permissionList.add(permission.getName()); permissionList.add(permission.getName());
} }
} }
@@ -52,12 +55,14 @@ public class AuthRealm extends AuthorizingRealm {
} }
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissionList); info.addStringPermissions(permissionList);
info.addRoles(roleList);
return info; return info;
} }
/** /**
* 认证登录 * 认证登录
*
* @param authenticationToken * @param authenticationToken
* @return * @return
* @throws AuthenticationException * @throws AuthenticationException
@@ -69,6 +74,6 @@ public class AuthRealm extends AuthorizingRealm {
String username = usernamePasswordToken.getUsername(); String username = usernamePasswordToken.getUsername();
// 通过用户名查用户是否存在,合法则登录认证通过 // 通过用户名查用户是否存在,合法则登录认证通过
User user = userService.findByUsername(username); User user = userService.findByUsername(username);
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName()); return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
} }
} }

View File

@@ -2,28 +2,28 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="top.fjy8018.shiro.mapper.UserMapper"> <mapper namespace="top.fjy8018.shiro.mapper.UserMapper">
<resultMap id="userMap" type="top.fjy8018.shiro.dataobject.User" > <resultMap id="userMap" type="top.fjy8018.shiro.dataobject.User">
<id property="uid" column="uid"/> <id property="uid" column="uid"/>
<result property="username" column="username" /> <result property="username" column="username"/>
<result property="password" column="password" /> <result property="password" column="password"/>
<collection property="roles" ofType="top.fjy8018.shiro.dataobject.Role"> <collection property="roles" ofType="top.fjy8018.shiro.dataobject.Role">
<id property="rid" column="rid" /> <id property="rid" column="rid"/>
<result property="rname" column="rname" /> <result property="rname" column="rname"/>
<collection property="permissions" ofType="top.fjy8018.shiro.dataobject.Permission"> <collection property="permissions" ofType="top.fjy8018.shiro.dataobject.Permission">
<id property="pid" column="pid" /> <id property="pid" column="pid"/>
<result property="name" column="name" /> <result property="name" column="name"/>
<result property="url" column="url" /> <result property="url" column="url"/>
</collection> </collection>
</collection> </collection>
</resultMap> </resultMap>
<select id="findByUsername" parameterType="java.lang.String" resultMap="userMap"> <select id="findByUsername" parameterType="java.lang.String" resultMap="userMap">
SELECT u.*,r.*,p.* SELECT u.*,r.*,p.*
FROM user u FROM user u
INNER JOIN user_role ur ON ur.uid = u.uid INNER JOIN user_role ur ON ur.uid = u.uid
INNER JOIN role r ON ur.uid = r.rid INNER JOIN role r ON ur.uid = r.rid
INNER JOIN permission_role pr ON r.rid = pr.rid INNER JOIN permission_role pr ON r.rid = pr.rid
INNER JOIN permission p ON pr.pid = p.pid INNER JOIN permission p ON pr.pid = p.pid
WHERE u.username = #{username} WHERE u.username = #{username}
</select> </select>
</mapper> </mapper>

View File

@@ -9,8 +9,8 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest @SpringBootTest
public class ShiroApplicationTests { public class ShiroApplicationTests {
@Test @Test
public void contextLoads() { public void contextLoads() {
} }
} }