• SSM整合shiro


    1.完成ssm整合shiro

    企业中老项目还在使用ssm框架

    (1)创建一个maven的web工程。

    (2)ssm整合到web工程

    pom依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframeworkgroupId>
    4. <artifactId>spring-webmvcartifactId>
    5. <version>5.2.15.RELEASEversion>
    6. dependency>
    7. <dependency>
    8. <groupId>org.mybatisgroupId>
    9. <artifactId>mybatisartifactId>
    10. <version>3.5.6version>
    11. dependency>
    12. <dependency>
    13. <groupId>org.mybatisgroupId>
    14. <artifactId>mybatis-springartifactId>
    15. <version>2.0.6version>
    16. dependency>
    17. <dependency>
    18. <groupId>mysqlgroupId>
    19. <artifactId>mysql-connector-javaartifactId>
    20. <version>8.0.28version>
    21. dependency>
    22. <dependency>
    23. <groupId>com.alibabagroupId>
    24. <artifactId>druidartifactId>
    25. <version>1.2.1version>
    26. dependency>
    27. <dependency>
    28. <groupId>org.projectlombokgroupId>
    29. <artifactId>lombokartifactId>
    30. <version>1.18.24version>
    31. dependency>
    32. <dependency>
    33. <groupId>com.fasterxml.jackson.coregroupId>
    34. <artifactId>jackson-databindartifactId>
    35. <version>2.13.2.2version>
    36. dependency>
    37. <dependency>
    38. <groupId>javax.servletgroupId>
    39. <artifactId>javax.servlet-apiartifactId>
    40. <version>4.0.1version>
    41. dependency>
    42. <dependency>
    43. <groupId>org.springframeworkgroupId>
    44. <artifactId>spring-jdbcartifactId>
    45. <version>5.2.15.RELEASEversion>
    46. dependency>
    47. <dependency>
    48. <groupId>org.springframeworkgroupId>
    49. <artifactId>spring-txartifactId>
    50. <version>5.2.15.RELEASEversion>
    51. dependency>
    52. <dependency>
    53. <groupId>org.springframeworkgroupId>
    54. <artifactId>spring-aspectsartifactId>
    55. <version>5.2.15.RELEASEversion>
    56. dependency>
    57. <dependency>
    58. <groupId>org.mybatis.generatorgroupId>
    59. <artifactId>mybatis-generator-coreartifactId>
    60. <version>1.4.0version>
    61. dependency>
    62. <dependency>
    63. <groupId>com.github.pagehelpergroupId>
    64. <artifactId>pagehelperartifactId>
    65. <version>5.3.0version>
    66. dependency>
    67. <dependency>
    68. <groupId>log4jgroupId>
    69. <artifactId>log4jartifactId>
    70. <version>1.2.17version>
    71. dependency>
    72. dependencies>

    spring配置文件

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    7. <context:component-scan base-package="com.wzh"/>
    8. <mvc:annotation-driven />
    9. <mvc:default-servlet-handler/>
    10. <bean id="lifecycleBeanPostProcessor"
    11. class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    12. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    13. depends-on="lifecycleBeanPostProcessor" />
    14. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    15. <property name="securityManager" ref="securityManager" />
    16. bean>
    17. <bean id="dataResource" class="com.alibaba.druid.pool.DruidDataSource">
    18. <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    19. <property name="url" value="jdbc:mysql://localhost:3306/shiro?serverTimezone=Asia/Shanghai"/>
    20. <property name="username" value="root"/>
    21. <property name="password" value="123456"/>
    22. <property name="initialSize" value="10"/>
    23. <property name="minIdle" value="5"/>
    24. <property name="maxActive" value="10"/>
    25. <property name="maxWait" value="2000"/>
    26. bean>
    27. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    28. <property name="dataSource" ref="dataResource"/>
    29. bean>
    30. <tx:annotation-driven transaction-manager="transactionManager"/>
    31. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    32. <property name="dataSource" ref="dataResource"/>
    33. <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    34. <property name="plugins" >
    35. <array>
    36. <bean class="com.github.pagehelper.PageInterceptor"/>
    37. array>
    38. property>
    39. bean>
    40. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    41. <property name="basePackage" value="com.wzh.mapper"/>
    42. bean>
    43. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    44. <property name="realm" ref="realm"/>
    45. bean>
    46. <bean id="realm" class="com.wzh.realm.MyRealm">
    47. <property name="credentialsMatcher" ref="credentialsMatcher"/>
    48. bean>
    49. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    50. <property name="hashAlgorithmName" value="MD5"/>
    51. <property name="hashIterations" value="1024"/>
    52. bean>
    53. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    54. <property name="securityManager" ref="securityManager"/>
    55. <property name="filterChainDefinitions">
    56. <value>
    57. /login=anon
    58. /**=authc
    59. value>
    60. property>
    61. <property name="filters">
    62. <map>
    63. <entry key="authc">
    64. <bean class="com.wzh.filter.LoginFilter"/>
    65. entry>
    66. map>
    67. property>
    68. bean>
    69. beans>

    web.xml配置文件

    1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    4. version="4.0">
    5. <filter>
    6. <filter-name>shiroFilterfilter-name>
    7. <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    8. filter>
    9. <filter-mapping>
    10. <filter-name>shiroFilterfilter-name>
    11. <url-pattern>/*url-pattern>
    12. filter-mapping>
    13. <servlet>
    14. <servlet-name>DispatcherServletservlet-name>
    15. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    16. <init-param>
    17. <param-name>contextConfigLocationparam-name>
    18. <param-value>classpath:springmvc.xmlparam-value>
    19. init-param>
    20. <load-on-startup>1load-on-startup>
    21. servlet>
    22. <servlet-mapping>
    23. <servlet-name>DispatcherServletservlet-name>
    24. <url-pattern>/url-pattern>
    25. servlet-mapping>
    26. <filter>
    27. <filter-name>encodingFilterfilter-name>
    28. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    29. <init-param>
    30. <param-name>encodingparam-name>
    31. <param-value>utf-8param-value>
    32. init-param>
    33. filter>
    34. <filter-mapping>
    35. <filter-name>encodingFilterfilter-name>
    36. <url-pattern>/*url-pattern>
    37. filter-mapping>
    38. web-app>

    准备数据库

     数据结构

    张三 -user:query user:add user:update user:delete

    李四 ---》user:query user:add user:update王五-----》user:query user:export

    搭建ssm的环境

    整合shiro

     

            (1)引入shiro的依赖

    1. <dependency>
    2. <groupId>org.apache.shirogroupId>
    3. <artifactId>shiro-springartifactId>
    4. <version>1.9.0version>
    5. dependency>

            (2)修改spring配置文件

    1. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    2. <property name="realm" ref="realm"/>
    3. bean>
    4. <bean id="realm" class="com.ykq.realm.MyRealm">
    5. <property name="credentialsMatcher" ref="credentialsMatcher"/>
    6. bean>
    7. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    8. <property name="hashAlgorithmName" value="MD5"/>
    9. <property name="hashIterations" value="1024"/>
    10. bean>
    11. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    12. <property name="loginUrl" value="/login.jsp"/>
    13. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    14. <property name="filterChainDefinitions">
    15. <value>
    16. /login=anon
    17. /**=authc
    18. value>
    19. property>
    20. bean>

    shiro中内置很多过滤器,而每个过滤都有相应的别名.

             (3) 修改web.xml文件

    1. <filter>
    2. <filter-name>shiroFilterfilter-name>
    3. <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    4. filter>
    5. <filter-mapping>
    6. <filter-name>shiroFilterfilter-name>
    7. <url-pattern>/*url-pattern>
    8. filter-mapping>

    1.1. 进入主页后,不同的用户可以看到不同的内容。

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: m1762
    4. Date: 2022/8/4
    5. Time: 22:58
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
    10. <html>
    11. <head>
    12. <title>Titletitle>
    13. head>
    14. <body>
    15. <shiro:hasPermission name="user:query">
    16. <a href="/query">查询用户a>
    17. shiro:hasPermission>
    18. <shiro:hasPermission name="user:add">
    19. <a href="/add">添加用户a>
    20. shiro:hasPermission>
    21. <shiro:hasPermission name="user:delete">
    22. <a href="/delete">删除用户a>
    23. shiro:hasPermission>
    24. <shiro:hasPermission name="user:update">
    25. <a href="/update">修改用户a>
    26. shiro:hasPermission>
    27. <shiro:hasPermission name="user:export">
    28. <a href="/export">导出用户a>
    29. shiro:hasPermission>
    30. body>
    31. html>

     

     可以在jsp中获取当前登录者的账号

    <h1>欢迎<shiro:principal property="username"/>来到主页h1>

     上面只是在网页中根据不同用户显示不同的菜单,这种方式只能防君子不能防小人。因为现在依旧可以通过postman访问没有的权限方法  比如张三可以访问到user:export路径

    解决办法:

    1. 拦截器---获取请求路径 然后根据你的路径判断当前用户是否具有该权限。

    2. spring整合shiro时提供了一个注解:可以加载相应方法上。

    使用注解:

    1.springmvc.xml中启动shiro的注解

    1. <bean id="lifecycleBeanPostProcessor"
    2. class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    3. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    4. depends-on="lifecycleBeanPostProcessor" />
    5. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    6. <property name="securityManager" ref="securityManager" />
    7. bean>

    (2)使用注解

     

    这个太丑了,我们想要跳转一个页面,

    我们之前学过全局异常处理:    没有登录会报这个异常

     

     

     

    2.ssm整合shiro完成前后端分离

    所谓前后端完全分离:后端响应的都是json数据,而不再是网页。  

    我们需要修改的就是:

    1. 登录成功或者失败应该返回json数据
    2. 当未登录时返回的也是json数据
    3. 访问未授权的资源,也要分会json。

    2.1.登录成功或者失败应该返回json数据

    修改登录接口

     

    2.2 当未登录时返回的也是json数据

    (1)创建一个过滤器,继承登录校验的FormAuthenticationFilter接口。

    1. package com.wzh.filter;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import com.wzh.utils.CommonResult;
    4. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
    5. import javax.servlet.ServletRequest;
    6. import javax.servlet.ServletResponse;
    7. import java.io.PrintWriter;
    8. /**
    9. * @ProjectName: shiro-ssm0805
    10. * @Package: com.wzh.filter
    11. * @ClassName: LoginFilter
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 16:58
    15. * @Version: 1.0
    16. */
    17. public class LoginFilter extends FormAuthenticationFilter {
    18. /**
    19. * 当没有登录时会经过该方法,如果想让它返回json数据必须重写onAccessDenied这个方法
    20. * @param request
    21. * @param response
    22. * @return
    23. * @throws Exception
    24. */
    25. @Override
    26. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    27. response.setContentType("application/json;charset=utf-8");
    28. PrintWriter writer = response.getWriter();
    29. CommonResult commonResult = CommonResult.UNLOGIN;
    30. //jackson中内置对象 将java对象转为json对象
    31. ObjectMapper objectMapper = new ObjectMapper();
    32. String json = objectMapper.writeValueAsString(commonResult);
    33. //响应给客户json数据
    34. writer.print(json);
    35. writer.flush();
    36. writer.close();
    37. return false;
    38. }
    39. }

    之前默认是在springmvc.xml中配置的跳转页面

    (2) 注册我们的过滤器

     

     2.3 如果没有权限应该返回json数据

     

    3.项目完整代码

    项目结构:

     

    Controller层:

     UserController:    用于登录    调用login方法判断是否身份认证  授权

    1. package com.wzh.controller;
    2. import com.wzh.utils.CommonResult;
    3. import org.apache.shiro.SecurityUtils;
    4. import org.apache.shiro.authc.UsernamePasswordToken;
    5. import org.apache.shiro.subject.Subject;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.PostMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RestController;
    10. /**
    11. * @ProjectName: ssm-shiro
    12. * @Package: com.wzh.controller
    13. * @ClassName: UserController
    14. * @Author: 王振华
    15. * @Description:
    16. * @Date: 2022/8/4 22:07
    17. * @Version: 1.0
    18. */
    19. @RestController
    20. public class UserController {
    21. @RequestMapping("login")
    22. public CommonResult login(String username,String password){
    23. System.out.println(username);
    24. //获取subject主体对象
    25. Subject subject = SecurityUtils.getSubject();
    26. UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    27. try{
    28. subject.login(token);
    29. System.out.println("是否身份认证:"+subject.isAuthenticated());
    30. System.out.println("是否授权:"+subject.isPermitted("查询"));
    31. System.out.println("是否授权:"+subject.isPermitted("添加"));
    32. System.out.println("是否授权:"+subject.isPermitted("修改"));
    33. System.out.println("是否授权:"+subject.isPermitted("删除"));
    34. System.out.println("是否授权:"+subject.isPermitted("导出"));
    35. System.out.println("是否授权:"+subject.hasRole("超级管理员"));
    36. System.out.println("是否授权:"+subject.hasRole("管理员"));
    37. System.out.println("是否授权:"+subject.hasRole("用户"));
    38. return CommonResult.LOGIN_SUCCESS;
    39. }catch (Exception e){
    40. e.printStackTrace();
    41. return CommonResult.LOGIN_ERROR;
    42. }
    43. }
    44. }

    PermissionController:      用于登录之后查看是否授权

    1. package com.wzh.controller;
    2. import com.wzh.utils.CommonResult;
    3. import org.apache.shiro.authz.annotation.Logical;
    4. import org.apache.shiro.authz.annotation.RequiresPermissions;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. /**
    9. * @ProjectName: shiro-ssm0805
    10. * @Package: com.wzh.controller
    11. * @ClassName: PermissionController
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 9:57
    15. * @Version: 1.0
    16. */
    17. @RestController
    18. public class PermissionController {
    19. @GetMapping("/query")
    20. //使用shiro注解
    21. @RequiresPermissions(value = {"user:query","user:aaa"},logical = Logical.OR)
    22. public String query(){
    23. return "query";
    24. }
    25. @RequestMapping("/add")
    26. @RequiresPermissions(value = {"user:add"})
    27. public String add(){
    28. return "add";
    29. }
    30. @RequestMapping("/delete")
    31. @RequiresPermissions(value = {"user:delete"})
    32. public String delete(){
    33. return "delete";
    34. }
    35. @RequestMapping("/update")
    36. @RequiresPermissions(value = {"user:update"})
    37. public String update(){
    38. return "update";
    39. }
    40. @RequestMapping("/export")
    41. @RequiresPermissions(value = {"user:export"})
    42. public String export(){
    43. return "export";
    44. }
    45. }

    service层:

    UserService:

    1. package com.wzh.service;
    2. import com.wzh.entity.User;
    3. import java.util.List;
    4. /**
    5. * @ProjectName: ssm-shiro
    6. * @Package: com.wzh.service
    7. * @ClassName: UserService
    8. * @Author: 王振华
    9. * @Description:
    10. * @Date: 2022/8/4 22:19
    11. * @Version: 1.0
    12. */
    13. public interface UserService {
    14. User findByUsername(String username);
    15. }

    PermissionService:

    1. package com.wzh.service;
    2. import java.util.List;
    3. /**
    4. * @ProjectName: ssm-shiro
    5. * @Package: com.wzh.service
    6. * @ClassName: PermissionService
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/4 22:27
    10. * @Version: 1.0
    11. */
    12. public interface PermissionService {
    13. List findPermissionById(Integer userid);
    14. }

    RoleService:

    1. package com.wzh.service;
    2. import java.util.List;
    3. /**
    4. * @ProjectName: ssm-shiro
    5. * @Package: com.wzh.service
    6. * @ClassName: RoleService
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/4 22:27
    10. * @Version: 1.0
    11. */
    12. public interface RoleService {
    13. List findRolesById(Integer userid);
    14. }

    UserServiceImpl:

    1. package com.wzh.service.impl;
    2. import com.wzh.entity.User;
    3. import com.wzh.mapper.UserMapper;
    4. import com.wzh.service.UserService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. /**
    9. * @ProjectName: ssm-shiro
    10. * @Package: com.wzh.service.impl
    11. * @ClassName: UserServiceImpl
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/4 22:20
    15. * @Version: 1.0
    16. */
    17. @Service
    18. public class UserServiceImpl implements UserService {
    19. @Autowired
    20. private UserMapper userMapper;
    21. @Override
    22. public User findByUsername(String username) {
    23. if(username!=null&&username!="") {
    24. User user = userMapper.selectByUsername(username);
    25. return user;
    26. }
    27. return null;
    28. }
    29. }

    PermissionServiceImpl:

    1. package com.wzh.service.impl;
    2. import com.wzh.mapper.PermissionMapper;
    3. import com.wzh.service.PermissionService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. /**
    9. * @ProjectName: ssm-shiro
    10. * @Package: com.wzh.service.impl
    11. * @ClassName: PermissionServiceImpl
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/4 22:28
    15. * @Version: 1.0
    16. */
    17. @Service
    18. public class PermissionServiceImpl implements PermissionService {
    19. @Autowired
    20. private PermissionMapper permissionMapper;
    21. @Override
    22. public List findPermissionById(Integer userid) {
    23. List list = permissionMapper.selectByUserId(userid);
    24. return list;
    25. }
    26. }

    RoleServiceImpl:

    1. package com.wzh.service.impl;
    2. import com.wzh.mapper.RoleMapper;
    3. import com.wzh.service.RoleService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import java.util.List;
    7. /**
    8. * @ProjectName: ssm-shiro
    9. * @Package: com.wzh.service.impl
    10. * @ClassName: RoleServiceImpl
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/4 22:28
    14. * @Version: 1.0
    15. */
    16. @Service
    17. public class RoleServiceImpl implements RoleService {
    18. @Autowired
    19. private RoleMapper roleMapper;
    20. @Override
    21. public List findRolesById(Integer userid) {
    22. List list = roleMapper.selectByUserId(userid);
    23. return list;
    24. }
    25. }

    mapper层:

    UserMapper:

    1. package com.wzh.mapper;
    2. import com.wzh.entity.User;
    3. import java.util.List;
    4. /**
    5. * @ProjectName: ssm-shiro
    6. * @Package: com.wzh.mapper
    7. * @ClassName: UserMapper
    8. * @Author: 王振华
    9. * @Description:
    10. * @Date: 2022/8/4 22:21
    11. * @Version: 1.0
    12. */
    13. public interface UserMapper {
    14. User selectByUsername(String username);
    15. }

    PermissionMapper:

    1. package com.wzh.mapper;
    2. import java.util.List;
    3. /**
    4. @ProjectName: ssm-shiro
    5. @Package: com.wzh.mapper
    6. @ClassName: PermissionMapper
    7. @Author: 王振华
    8. @Description:
    9. @Date: 2022/8/4 22:21
    10. @Version: 1.0
    11. */
    12. public interface PermissionMapper {
    13. List selectByUserId(Integer userid);
    14. }

    RoleMapper:

    1. package com.wzh.mapper;
    2. import java.util.List;
    3. /**
    4. * @ProjectName: ssm-shiro
    5. * @Package: com.wzh.mapper
    6. * @ClassName: RoleMapper
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/4 22:21
    10. * @Version: 1.0
    11. */
    12. public interface RoleMapper {
    13. List selectByUserId(Integer userid);
    14. }

    entity层:

    User:

    1. package com.wzh.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. import javax.management.relation.Role;
    6. /**
    7. * @ProjectName: ssm-shiro
    8. * @Package: com.wzh.entity
    9. * @ClassName: User
    10. * @Author: 王振华
    11. * @Description:
    12. * @Date: 2022/8/4 22:19
    13. * @Version: 1.0
    14. */
    15. @Data
    16. @NoArgsConstructor
    17. @AllArgsConstructor
    18. public class User {
    19. private Integer userid;
    20. private String username;
    21. private String userpwd;
    22. private String sex;
    23. private String address;
    24. private String salt;
    25. private Permission permission;
    26. private Role role;
    27. }

    Permission:

    1. package com.wzh.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @ProjectName: ssm-shiro
    7. * @Package: com.wzh.entity
    8. * @ClassName: Permission
    9. * @Author: 王振华
    10. * @Description:
    11. * @Date: 2022/8/4 22:22
    12. * @Version: 1.0
    13. */
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class Permission {
    18. private Integer perid;
    19. private String pername;
    20. private String percode;
    21. }

    Role:

    1. package com.wzh.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @ProjectName: ssm-shiro
    7. * @Package: com.wzh.entity
    8. * @ClassName: Role
    9. * @Author: 王振华
    10. * @Description:
    11. * @Date: 2022/8/4 22:22
    12. * @Version: 1.0
    13. */
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class Role {
    18. private Integer roleid;
    19. private String rolename;
    20. }

    filter:

    LoginFilter:   用于未登录返回json数据

    1. package com.wzh.filter;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import com.wzh.utils.CommonResult;
    4. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
    5. import javax.servlet.ServletRequest;
    6. import javax.servlet.ServletResponse;
    7. import java.io.PrintWriter;
    8. /**
    9. * @ProjectName: shiro-ssm0805
    10. * @Package: com.wzh.filter
    11. * @ClassName: LoginFilter
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 16:58
    15. * @Version: 1.0
    16. */
    17. public class LoginFilter extends FormAuthenticationFilter {
    18. /**
    19. * 当没有登录时会经过该方法,如果想让它返回json数据必须重写onAccessDenied这个方法
    20. * @param request
    21. * @param response
    22. * @return
    23. * @throws Exception
    24. */
    25. @Override
    26. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    27. response.setContentType("application/json;charset=utf-8");
    28. PrintWriter writer = response.getWriter();
    29. CommonResult commonResult = CommonResult.UNLOGIN;
    30. //jackson中内置对象 将java对象转为json对象
    31. ObjectMapper objectMapper = new ObjectMapper();
    32. String json = objectMapper.writeValueAsString(commonResult);
    33. //响应给客户json数据
    34. writer.print(json);
    35. writer.flush();
    36. writer.close();
    37. return false;
    38. }
    39. }

    handler:  全局异常处理类   用户没有权限返回json数据给前端

    MyException:

    1. package com.wzh.handler;
    2. import com.wzh.utils.CommonResult;
    3. import org.apache.shiro.authz.UnauthorizedException;
    4. import org.springframework.web.bind.annotation.ControllerAdvice;
    5. import org.springframework.web.bind.annotation.ExceptionHandler;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. /**
    8. * @ProjectName: shiro-ssm0805
    9. * @Package: com.wzh.handler
    10. * @ClassName: MyException
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/5 16:42
    14. * @Version: 1.0
    15. */
    16. @ControllerAdvice //异常处理类
    17. public class MyException {
    18. //当发生该异常时触发该方法
    19. @ExceptionHandler(value = UnauthorizedException.class)
    20. @ResponseBody
    21. public CommonResult Unauth(UnauthorizedException e){
    22. e.printStackTrace();
    23. return CommonResult.UNAUTHORIZED;
    24. }
    25. }

    realm:   自定义的认证授权规则

    MyRealm:

    1. package com.wzh.realm;
    2. import com.wzh.entity.User;
    3. import com.wzh.service.PermissionService;
    4. import com.wzh.service.RoleService;
    5. import com.wzh.service.UserService;
    6. import org.apache.shiro.authc.AuthenticationException;
    7. import org.apache.shiro.authc.AuthenticationInfo;
    8. import org.apache.shiro.authc.AuthenticationToken;
    9. import org.apache.shiro.authc.SimpleAuthenticationInfo;
    10. import org.apache.shiro.authz.AuthorizationInfo;
    11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
    12. import org.apache.shiro.realm.AuthorizingRealm;
    13. import org.apache.shiro.subject.PrincipalCollection;
    14. import org.apache.shiro.util.ByteSource;
    15. import org.springframework.beans.factory.annotation.Autowired;
    16. import java.util.List;
    17. /**
    18. * @ProjectName: shiro
    19. * @Package: com.wzh.demo02
    20. * @ClassName: MyRealm
    21. * @Author: 王振华
    22. * @Description:
    23. * @Date: 2022/8/4 19:44
    24. * @Version: 1.0
    25. */
    26. public class MyRealm extends AuthorizingRealm {
    27. @Autowired
    28. private UserService userService;
    29. @Autowired
    30. private PermissionService permissionService;
    31. @Autowired
    32. private RoleService roleService;
    33. @Override
    34. //该方法用于完成认证的功能
    35. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    36. //1.根据token获取账号
    37. String username = (String) authenticationToken.getPrincipal();
    38. /**
    39. * 以前登陆的逻辑是 把用户和密码全部发到数据库 去匹配
    40. * 在shrio里面是先根据用户名把用户对象查询出来,再来做密码匹配
    41. */
    42. //2.根据账号查询用户信息
    43. User user = userService.findByUsername(username);
    44. //表示该用户名在数据库中存在
    45. if(user!=null){
    46. /**
    47. * 参数说明
    48. * 参数1:可以传到任意对象
    49. * 参数2:从数据库里面查询出来的密码
    50. * 参数3:盐
    51. * 参数4:当前类名
    52. */
    53. ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
    54. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUserpwd(),credentialsSalt,this.getName());
    55. return info;
    56. }
    57. //用户不存在 shiro会抛 UnknowAccountException
    58. return null;
    59. }
    60. //授权
    61. @Override
    62. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    63. User user = (User) principalCollection.getPrimaryPrincipal();
    64. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    65. //根据账号查找该用户具有哪些权限
    66. List list = permissionService.findPermissionById(user.getUserid());
    67. if(list!=null&&list.size()>0){
    68. info.addStringPermissions(list);
    69. }
    70. List roles = roleService.findRolesById(user.getUserid());
    71. if(roles!=null&&roles.size()>0){
    72. info.addRoles(roles);
    73. }
    74. return info;
    75. }
    76. }

    util:

    CommonResult:

    1. package com.wzh.utils;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @ProjectName: shiro-ssm0805
    7. * @Package: com.wzh.utils
    8. * @ClassName: CommonResult
    9. * @Author: 王振华
    10. * @Description:
    11. * @Date: 2022/8/5 11:02
    12. * @Version: 1.0
    13. */
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class CommonResult {
    18. public static final CommonResult UNLOGIN = new CommonResult(403,"未登录",null);
    19. public static final CommonResult UNAUTHORIZED = new CommonResult(405,"未授权",null);
    20. public static final CommonResult LOGIN_SUCCESS = new CommonResult(200,"登录成功",null);
    21. public static final CommonResult LOGIN_ERROR = new CommonResult(-1,"登录失败",null);
    22. private Integer code;
    23. private String msg;
    24. private Object data;
    25. }

     

  • 相关阅读:
    Java集合Map接口详解——含源码分析
    【论文翻译】分布式数据库系统中的并发控制
    第1章 数据结构的概念
    为什么在listview上只显示一行,不论list有几个数据,都只显示第一行的
    VMware-vSphere 文档
    推荐两款不错的打字练习网站~
    个人述职报告
    csmall-passport(Day15)
    [附源码]计算机毕业设计JAVA校园失物招领平台
    代码随想录算法训练营第一天 | 704. 二分查找、27. 移除元素
  • 原文地址:https://blog.csdn.net/weixin_68509156/article/details/126186110