# 初步认识 shiro
AuthorizingRealm 抽象类中有两大方法 doGetAuthenticationInfo() 和 doGetAuthorizationInfo()
doGetAuthenticationInfo(),方法完成了用户认证操作
doGetAuthorizationInfo(),方法完成Shiro的权限控制功能
doGetAuthenticationInfo()方法已经在 spring boot 整合 shiro + jwt 中实现了,接下来权限管理需要实现 doGetAuthorizationInfo() 方法
# 新建五个数据库表
permission(权限表),role(角色表),role_permission(角色权限表),user(用户表),user_role(用户角色表)
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`url` varchar(255) DEFAULT '' COMMENT 'url地址',
`name` varchar(255) DEFAULT NULL COMMENT 'url描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL COMMENT '角色名称',
`memo` varchar(255) DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) DEFAULT NULL COMMENT '角色id',
`permission_id` int(11) DEFAULT NULL COMMENT '权限id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(255) DEFAULT NULL COMMENT '用户名',
`password` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL COMMENT '用户id',
`role_id` int(11) DEFAULT NULL COMMENT '角色id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
# Dao层
UserDao
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface UserDao {
int add(UserBean userBean);
int update(UserBean userBean);
void delete(Long id);
UserBean queryById(Long id);
List<UserBean> list();
UserBean queryByUser(String user);
}
PermissionDao
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface PermissionDao {
int add(PermissionBean permissionBean);
int update(PermissionBean permissionBean);
void delete(Long id);
PermissionBean queryById(Long id);
List<PermissionBean> list(PermissionBean permissionBean);
}
RoleDao
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface RoleDao {
int add(RoleBean roleBean);
int update(RoleBean roleBean);
void delete(Long id);
RoleBean queryById(Long id);
List<RoleBean> list(RoleBean roleBean);
}
RolePermissionDao
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface RolePermissionDao {
int add(RolePermissionBean rolePermissionBean);
int update(RolePermissionBean rolePermissionBean);
void delete(Long id);
RolePermissionBean queryById(Long id);
List<RolePermissionBean> list(RolePermissionBean rolePermissionBean);
}
UserRoleDao
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface UserRoleDao {
int add(UserRoleBean userRoleBean);
int update(UserRoleBean userRoleBean);
void delete(Long id);
UserRoleBean queryById(Long id);
List<UserRoleBean> list(UserRoleBean userRoleBean);
}
# Mapper.xml
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.chenbz.shiro.system.user.dao.UserDao">
<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.chenbz.shiro.system.user.bean.UserBean">
INSERT INTO user (user, password, name)
VALUES (#{user},#{password},#{name})
</insert>
<update id="update" parameterType="com.chenbz.shiro.system.user.bean.UserBean">
UPDATE user
<set>
<if test="user != null">user=#{user},</if>
<if test="password != null">password=#{password},</if>
<if test="name != null">name=#{name},</if>
</set>
WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id=#{id}
</delete>
<select id="queryById" parameterType="Long" resultType="com.chenbz.shiro.system.user.bean.UserBean">
SELECT * FROM user WHERE id=#{id}
</select>
<select id="list" resultType="com.chenbz.shiro.system.user.bean.UserBean">
SELECT * FROM user
</select>
<select id="queryByUser" parameterType="String" resultType="com.chenbz.shiro.system.user.bean.UserBean">
SELECT * FROM user WHERE user=#{user}
</select>
</mapper>
PermissionMapper.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.chenbz.shiro.system.user.dao.PermissionDao">
<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.chenbz.shiro.system.user.bean.PermissionBean">
INSERT INTO permission (url, name)
VALUES (#{url},#{name})
</insert>
<update id="update" parameterType="com.chenbz.shiro.system.user.bean.PermissionBean">
UPDATE permission
<set>
<if test="url != null">url=#{url},</if>
<if test="name != null">name=#{name},</if>
</set>
WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM permission WHERE id=#{id}
</delete>
<select id="queryById" parameterType="Long" resultType="com.chenbz.shiro.system.user.bean.PermissionBean">
SELECT * FROM permission WHERE id=#{id}
</select>
<select id="list" resultType="com.chenbz.shiro.system.user.bean.PermissionBean">
SELECT * FROM permission
<where>
<if test="id != null">AND id=#{id}</if>
<if test="url != null">AND url=#{url}</if>
<if test="name != null">AND name=#{name},</if>
</where>
</select>
</mapper>
RoleMapper.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.chenbz.shiro.system.user.dao.RoleDao">
<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.chenbz.shiro.system.user.bean.RoleBean">
INSERT INTO role (name, memo)
VALUES (#{name},#{memo})
</insert>
<update id="update" parameterType="com.chenbz.shiro.system.user.bean.RoleBean">
UPDATE role
<set>
<if test="name != null">name=#{name},</if>
<if test="memo != null">memo=#{memo},</if>
</set>
WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM role WHERE id=#{id}
</delete>
<select id="queryById" parameterType="Long" resultType="com.chenbz.shiro.system.user.bean.RoleBean">
SELECT * FROM role WHERE id=#{id}
</select>
<select id="list" resultType="com.chenbz.shiro.system.user.bean.RoleBean">
SELECT * FROM role
<where>
<if test="id != null">AND id=#{id}</if>
<if test="name != null">AND name=#{name}</if>
<if test="memo != null">AND memo=#{memo},</if>
</where>
</select>
</mapper>
RolePermissionMapper.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.chenbz.shiro.system.user.dao.RolePermissionDao">
<resultMap id="role-permission" type="com.chenbz.shiro.system.user.bean.RolePermissionBean">
<id column="id" property="id"></id>
<result column="role_id" property="roleId"></result>
<result column="permission_id" property="permissionId"></result>
<collection property="roleBean" column="role_id"
select="com.chenbz.shiro.system.user.dao.RoleDao.queryById">
</collection>
<collection property="permissionBean" column="permission_id"
select="com.chenbz.shiro.system.user.dao.PermissionDao.queryById">
</collection>
</resultMap>
<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.chenbz.shiro.system.user.bean.RolePermissionBean">
INSERT INTO role_permission (role_id, permission_id)
VALUES (#{roleId},#{permissionId})
</insert>
<update id="update" parameterType="com.chenbz.shiro.system.user.bean.RolePermissionBean">
UPDATE role_permission
<set>
<if test="roleId != null">role_id=#{roleId},</if>
<if test="permissionId != null">permission_id=#{permissionId},</if>
</set>
WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM role_permission WHERE id=#{id}
</delete>
<select id="queryById" parameterType="Long" resultMap="role-permission">
SELECT * FROM role_permission WHERE id=#{id}
</select>
<select id="list" resultMap="role-permission">
SELECT * FROM role_permission
<where>
<if test="id != null">AND id=#{id}</if>
<if test="roleId != null">AND role_id=#{roleId}</if>
<if test="permissionId != null">AND permission_id=#{permissionId},</if>
</where>
</select>
</mapper>
UserRoleMapper.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.chenbz.shiro.system.user.dao.UserRoleDao">
<resultMap id="user-role" type="com.chenbz.shiro.system.user.bean.UserRoleBean">
<id column="id" property="id"></id>
<result column="user_id" property="userId"></result>
<result column="role_id" property="roleId"></result>
<collection property="userBean" column="user_id"
select="com.chenbz.shiro.system.user.dao.UserDao.queryById">
</collection>
<collection property="roleBean" column="role_id"
select="com.chenbz.shiro.system.user.dao.RoleDao.queryById">
</collection>
</resultMap>
<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.chenbz.shiro.system.user.bean.UserRoleBean">
INSERT INTO user_role (user_id, role_id)
VALUES (#{userId},#{roleId})
</insert>
<update id="update" parameterType="com.chenbz.shiro.system.user.bean.UserRoleBean">
UPDATE user_role
<set>
<if test="userId != null">user_id=#{userId},</if>
<if test="roleId != null">role_id=#{roleId},</if>
</set>
WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM user_role WHERE id=#{id}
</delete>
<select id="queryById" parameterType="Long" resultMap="user-role">
SELECT * FROM user_role WHERE id=#{id}
</select>
<select id="list" resultMap="user-role">
SELECT * FROM user_role
<where>
<if test="id != null">AND id=#{id}</if>
<if test="userId != null">AND user_id=#{userId}</if>
<if test="roleId != null">AND role_id=#{roleId},</if>
</where>
</select>
</mapper>
# ShiroRealm.class
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private UserRoleService userRoleService;
@Autowired
private RolePermissionService rolePermissionService;
@Autowired
private PermissionService permissionService;
@Autowired
private RoleService roleService;
/**
* 必须重写此方法,不然Shiro会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
/**
* 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission之类的
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = JwtUtil.getUsername(principals.toString());
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
UserBean userBean = userService.queryByUser(username);
/*
* 根据用户 id 去查询角色集
* */
List<UserRoleBean> listUserRole = userRoleService.list(new UserRoleBean().setUserId(userBean.getId()));
for (UserRoleBean uR: listUserRole) {
/*
* 根据角色去查询角色权限集
* */
for (RolePermissionBean rP: rolePermissionService.list(new RolePermissionBean().setRoleId(uR.getRoleId()))) {
/*
* 根据权限 id 查询到角色信息
* 添加到 shiro 权限集中去
* */
for (PermissionBean p: permissionService.list(new PermissionBean().setId(rP.getPermissionId()))) {
simpleAuthorizationInfo.addStringPermission(p.getUrl());
}
}
/*
* 获取角色 id
* 根据角色 id 去 role表查询角色名字
* 添加到 shiro 角色中去
* */
simpleAuthorizationInfo.addRole(roleService.queryById(uR.getRoleId()).getName());
}
return simpleAuthorizationInfo;
}
/**
* 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JwtUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token无效");
}
/*
* 通过用户名到数据库查询用户信息
* */
UserBean userBean = userService.queryByUser(username);
if (userBean == null) {
throw new AuthenticationException("用户不存在!");
}
if (!JwtUtil.verify(token, username, userBean.getPassword())) {
throw new AuthenticationException("用户名或密码错误");
}
return new SimpleAuthenticationInfo(token, token, "shiro_realm");
}
}
# ShiroConfig.class
Shiro为我们提供了一些和权限相关的注解,如下所示:
// 表示当前Subject已经通过login进行了身份验证;即Subject.isAuthenticated()返回true。
@RequiresAuthentication
// 表示当前Subject已经身份验证或者通过记住我登录的。
@RequiresUser
// 表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
@RequiresGuest
// 表示当前Subject需要角色admin和user。
@RequiresRoles(value={"admin", "user"}, logical= Logical.AND)
// 表示当前Subject需要权限user:a或user:b。
@RequiresPermissions (value={"user:a", "user:b"}, logical= Logical.OR)
要开启这些注解的使用,需要在ShiroConfig中添加如下配置:
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
完整 ShiroConfig.class 代码:
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager); // 设置securityManager
//拦截器
/*
* 配置shiro拦截器链
*
* anon 不需要认证
* authc 需要认证
* user 验证通过或RememberMe登录的都可以
*
* 当应用开启了rememberMe时,用户下次访问时可以是一个user,但不会是authc,因为authc是需要重新认证的
*
* 顺序从上到下,优先级依次降低
*
*/
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/api/user/login", "anon"); // 用户登录接口
filterChainDefinitionMap.put("/api/user/logout", "anon"); // 用户退出登录接口
filterChainDefinitionMap.put("/druid/**", "anon"); // 放行 druid 数据源监控页面不拦截
/*
* 放行 swagger 页面
* */
filterChainDefinitionMap.put("/swagger**/**", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/v2/**", "anon");
// 添加自己的过滤器并且取名为jwt
Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
filterMap.put("jwt", new JwtFilter());
shiroFilterFactoryBean.setFilters(filterMap);
//<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边
filterChainDefinitionMap.put("/**", "jwt");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean("securityManager")
public SecurityManager securityManager(ShiroRealm shiroRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
/*
* 关闭shiro自带的session,详情见文档
* http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
*/
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
securityManager.setSubjectDAO(subjectDAO);
securityManager.setRealm(shiroRealm);
return securityManager;
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
# bean层,service层代码就不贴了,可以自己实现
# Controller层
UserController
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
@Api(value = "用户表接口")
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseApiController {
@Autowired
private UserService userService;
@ApiOperation("添加用户")
@RequiresPermissions("user:add")
@PostMapping("/add")
public Map<String, Object> add(String user,
String password,
String name)
{
UserBean userBean = new UserBean()
.setUser(user)
.setPassword(password)
.setName(name);
if (userService.add(userBean)==0) {
return resp(406,"添加失败");
} else {
return resp(200, "添加成功", userBean);
}
}
@ApiOperation("修改用户信息")
@RequiresPermissions("user:update")
@PostMapping("/update")
public Map<String, Object> update(Long id,
String user,
String password,
String name) {
UserBean userBean = new UserBean()
.setId(id)
.setUser(user)
.setPassword(password)
.setName(name);
return resp(200, "修改成功", userService.update(userBean));
}
@ApiOperation("删除用户")
@RequiresPermissions("user:delete")
@PostMapping("/delete")
public Map<String, Object> deleteById(Long id) {
userService.delete(id);
return resp(200, "删除成功");
}
@ApiOperation("根据id查询用户信息")
@RequiresPermissions("user:query")
@GetMapping("/query")
public Map<String, Object> queryById(Long id) {
return resp(200, "查询成功", userService.queryById(id));
}
@ApiOperation("查询所有用户信息")
@RequiresPermissions("user:list")
@GetMapping("/list")
public Map<String, Object> list(int pageNum,
int pageSize)
{
PageHelper.startPage(pageNum, pageSize); // 传入查询的页码,以及显示的条数
PageHelper.orderBy("id asc"); // 字段"id"升序输出, desc为降序,asc为升序
List<UserBean> list = userService.list();
PageInfo<UserBean> pageInfo = new PageInfo<UserBean>(list); // 使用pageInfo包装查询后的结果,封装了详细的查询数据
return resp(200, "查询所有成功", pageInfo);
}
@ApiOperation("根据账号查询用户")
@GetMapping("/query/user")
public Map<String, Object> queryByName(String user) {
return resp(200, "查询成功", userService.queryByUser(user));
}
@ApiOperation("用户登录")
@PostMapping("/login")
public Map<String, Object> login (HttpServletResponse response, String user, String password) throws IOException {
UserBean userBean = userService.queryByUser(user);
if (userBean != null) {
if (password.equals(userBean.getPassword())) {
Cookie cookie = new Cookie("token", URLEncoder.encode(JwtUtil.sign(user, password),"UTF-8"));
// cookie.setMaxAge(5 * 60 * 24);
cookie.setPath("/");
response.addCookie(cookie);
return resp(200,"登录成功", userBean);
} else {
return resp(10011,"密码错误");
}
}
return resp(10001, "没有该用户");
}
@ApiOperation("用户退出登录")
@GetMapping("/logout")
public Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response) {
JwtUtil.signOut(request, response);
return resp(200, "退出登录成功");
}
}
PermissionController
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@Api(value = "权限表接口")
@RestController
@RequestMapping("/api/permission")
public class PermissionController extends BaseApiController {
@Autowired
private PermissionService permissionService;
@ApiOperation("添加权限")
@RequiresPermissions("permission:add")
@PostMapping("/add")
public Map<String, Object> add(String url,
String name)
{
PermissionBean permissionBean = new PermissionBean()
.setUrl(url)
.setName(name);
if (permissionService.add(permissionBean)==0) {
return resp(406,"添加失败");
} else {
return resp(200, "添加成功", permissionBean);
}
}
@ApiOperation("修改权限信息")
@RequiresPermissions("permission:update")
@PostMapping("/update")
public Map<String, Object> update(Long id,
String url,
String name) {
PermissionBean permissionBean = new PermissionBean()
.setId(id)
.setUrl(url)
.setName(name);
return resp(200, "修改成功", permissionService.update(permissionBean));
}
@ApiOperation("删除权限")
@RequiresPermissions("permission:delete")
@PostMapping("/delete")
public Map<String, Object> deleteById(Long id) {
permissionService.delete(id);
return resp(200, "删除成功");
}
@ApiOperation("根据id查询权限信息")
@GetMapping("/query")
public Map<String, Object> queryById(Long id) {
return resp(200, "查询成功", permissionService.queryById(id));
}
@ApiOperation("查询所有权限信息")
@GetMapping("/list")
public Map<String, Object> list(int pageNum,
int pageSize,
Long id,
String url,
String name) {
PermissionBean permissionBean = new PermissionBean()
.setId(id)
.setUrl(url)
.setName(name);
PageHelper.startPage(pageNum, pageSize); // 传入查询的页码,以及显示的条数
PageHelper.orderBy("id asc"); // 字段"id"升序输出, desc为降序,asc为升序
List<PermissionBean> list = permissionService.list(permissionBean);
PageInfo<PermissionBean> pageInfo = new PageInfo<PermissionBean>(list); // 使用pageInfo包装查询后的结果,封装了详细的查询数据
return resp(200, "查询所有成功", pageInfo);
}
}
RoleController
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@Api(value = "角色表接口")
@RestController
@RequestMapping("/api/role")
public class RoleController extends BaseApiController {
@Autowired
private RoleService roleService;
@ApiOperation("添加角色")
@RequiresPermissions("role:add")
@PostMapping("/add")
public Map<String, Object> add(String name,
String memo)
{
RoleBean roleBean = new RoleBean()
.setName(name)
.setMemo(memo);
if (roleService.add(roleBean)==0) {
return resp(406,"添加失败");
} else {
return resp(200, "添加成功", roleBean);
}
}
@ApiOperation("修改角色信息")
@RequiresPermissions("role:update")
@PostMapping("/update")
public Map<String, Object> update(Long id,
String name,
String memo) {
RoleBean roleBean = new RoleBean()
.setId(id)
.setName(name)
.setMemo(memo);
return resp(200, "修改成功", roleService.update(roleBean));
}
@ApiOperation("删除角色")
@RequiresPermissions("role:delete")
@PostMapping("/delete")
public Map<String, Object> deleteById(Long id) {
roleService.delete(id);
return resp(200, "删除成功");
}
@ApiOperation("根据id查询角色信息")
@GetMapping("/query")
public Map<String, Object> queryById(Long id) {
return resp(200, "查询成功", roleService.queryById(id));
}
@ApiOperation("查询所有角色信息")
@GetMapping("/list")
public Map<String, Object> list(int pageNum,
int pageSize,
Long id,
String name,
String memo) {
RoleBean roleBean = new RoleBean()
.setId(id)
.setName(name)
.setMemo(memo);
PageHelper.startPage(pageNum, pageSize); // 传入查询的页码,以及显示的条数
PageHelper.orderBy("id asc"); // 字段"id"升序输出, desc为降序,asc为升序
List<RoleBean> list = roleService.list(roleBean);
PageInfo<RoleBean> pageInfo = new PageInfo<RoleBean>(list); // 使用pageInfo包装查询后的结果,封装了详细的查询数据
return resp(200, "查询所有成功", pageInfo);
}
}
RolePermissionController
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@Api(value = "角色权限表接口")
@RestController
@RequestMapping("/api/role/permission")
public class RolePermissionController extends BaseApiController {
@Autowired
private RolePermissionService rolePermissionService;
@ApiOperation("添加角色权限")
@RequiresPermissions("role:permission:add")
@PostMapping("/add")
public Map<String, Object> add(Long roleId,
Long permissionId)
{
RolePermissionBean rolePermissionBean = new RolePermissionBean()
.setRoleId(roleId)
.setPermissionId(permissionId);
if (rolePermissionService.add(rolePermissionBean)==0) {
return resp(406,"添加失败");
} else {
return resp(200, "添加成功", rolePermissionBean);
}
}
@ApiOperation("修改角色权限信息")
@RequiresPermissions("role:permission:update")
@PostMapping("/update")
public Map<String, Object> update(Long id,
Long roleId,
Long permissionId) {
RolePermissionBean rolePermissionBean = new RolePermissionBean()
.setId(id)
.setRoleId(roleId)
.setPermissionId(permissionId);
return resp(200, "修改成功", rolePermissionService.update(rolePermissionBean));
}
@ApiOperation("删除角色权限")
@RequiresPermissions("role:permission:delete")
@PostMapping("/delete")
public Map<String, Object> deleteById(Long id) {
rolePermissionService.delete(id);
return resp(200, "删除成功");
}
@ApiOperation("根据id查询角色权限信息")
@GetMapping("/query")
public Map<String, Object> queryById(Long id) {
return resp(200, "查询成功", rolePermissionService.queryById(id));
}
@ApiOperation("查询所有角色权限信息")
@GetMapping("/list")
public Map<String, Object> list(int pageNum,
int pageSize,
Long id,
Long roleId,
Long permissionId) {
RolePermissionBean rolePermissionBean = new RolePermissionBean()
.setId(id)
.setRoleId(roleId)
.setPermissionId(permissionId);
PageHelper.startPage(pageNum, pageSize); // 传入查询的页码,以及显示的条数
PageHelper.orderBy("id asc"); // 字段"id"升序输出, desc为降序,asc为升序
List<RolePermissionBean> list = rolePermissionService.list(rolePermissionBean);
PageInfo<RolePermissionBean> pageInfo = new PageInfo<RolePermissionBean>(list); // 使用pageInfo包装查询后的结果,封装了详细的查询数据
return resp(200, "查询所有成功", pageInfo);
}
}
UserRoleController
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@Api(value = "用户角色表接口")
@RestController
@RequestMapping("/api/user/role")
public class UserRoleController extends BaseApiController {
@Autowired
private UserRoleService userRoleService;
@ApiOperation("添加用户角色")
@RequiresPermissions("user:role:add")
@PostMapping("/add")
public Map<String, Object> add(Long userId,
Long roleId)
{
UserRoleBean userRoleBean = new UserRoleBean()
.setUserId(userId)
.setRoleId(roleId);
if (userRoleService.add(userRoleBean)==0) {
return resp(406,"添加失败");
} else {
return resp(200, "添加成功", userRoleBean);
}
}
@ApiOperation("修改用户角色信息")
@RequiresPermissions("user:role:update")
@PostMapping("/update")
public Map<String, Object> update(Long id,
Long userId,
Long roleId) {
UserRoleBean userRoleBean = new UserRoleBean()
.setId(id)
.setUserId(userId)
.setRoleId(roleId);
return resp(200, "修改成功", userRoleService.update(userRoleBean));
}
@ApiOperation("删除用户角色")
@RequiresPermissions("user:role:delete")
@PostMapping("/delete")
public Map<String, Object> deleteById(Long id) {
userRoleService.delete(id);
return resp(200, "删除成功");
}
@ApiOperation("根据id查询用户角色信息")
@GetMapping("/query")
public Map<String, Object> queryById(Long id) {
return resp(200, "查询成功", userRoleService.queryById(id));
}
@ApiOperation("查询所有用户角色信息")
@GetMapping("/list")
public Map<String, Object> list(int pageNum,
int pageSize,
Long id,
Long userId,
Long roleId) {
UserRoleBean userRoleBean = new UserRoleBean()
.setId(id)
.setUserId(userId)
.setRoleId(roleId);
PageHelper.startPage(pageNum, pageSize); // 传入查询的页码,以及显示的条数
PageHelper.orderBy("id asc"); // 字段"id"升序输出, desc为降序,asc为升序
List<UserRoleBean> list = userRoleService.list(userRoleBean);
PageInfo<UserRoleBean> pageInfo = new PageInfo<UserRoleBean>(list); // 使用pageInfo包装查询后的结果,封装了详细的查询数据
return resp(200, "查询所有成功", pageInfo);
}
}
参考博客:https://mrbird.cc/Spring-Boot-Shiro%20Authorization.html