ssm整合shiro

目录

1 创建一个maven的web工程。

2 ssm整合到web工程----省略

3 整合shiro


1 创建一个maven的web工程。

2 ssm整合到web工程----省略

pom依赖

spring配置文件

web.xml配置文件

3 整合shiro

(1)引入shiro的依赖

 <!--shiro-->
 <dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.9.0</version>
 </dependency>

(2)修改spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--包扫描-->
    <context:component-scan base-package="com.xzj"/>
    <!--开启注解-->
    <mvc:annotation-driven/>
    <!--静态资源的放行-->
    <mvc:default-servlet-handler/>



    <!--spring的配置-->
    <!--数据源配置-->
    <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
        <!--驱动名称-->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm_shiro?serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <!--初始化连接池的个数-->
        <property name="initialSize" value="5"/>
        <!--至少的个数-->
        <property name="minIdle" value="5"/>
        <!--最多的个数-->
        <property name="maxActive" value="10"/>
        <!--最长等待时间单位毫秒-->
        <property name="maxWait" value="3000"/>
    </bean>

    <!--sqlSessionFactory 整合mybatis-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds"/>
        <!--设置mybatis映射文件的路径-->
        <!--        <property name="mapperLocations" value="classpath:mapper/*.xml"/>-->
        <!---->
    </bean>

    <!--为dao接口生成代理实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--为com.ykq.dao包下的接口生成代理实现类-->
        <property name="basePackage" value="com.xzj.dao"/>
    </bean>

    <!--事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds"/>
    </bean>

    <!--开启事务管理-->
    <tx:annotation-driven transaction-manager="transactionManager"/>


    <!--整合shiro的配置内容-->
    <!--①SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="realm"/>
    </bean>

    <!--创建自定义realm类对象-->
    <bean id="realm" class="com.xzj.realm.MyRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

    <!--创建密码匹配器-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="MD5"/>
        <property name="hashIterations" value="1024"/>
    </bean>

    <!--shiro过滤工厂: 设置过滤的规则-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--如果没有登录,跳转的路径-->
        <property name="loginUrl" value="/login.jsp"/>
        <!--没有权限,跳转的路径-->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>

        <property name="filterChainDefinitions">
            <value>
                /login=anon
                /**=authc
            </value>
        </property>
        <property name="filters">
            <map>
                <entry key="authc">
                    <bean class="com.xzj.filter.LoginFilter"/>
                </entry>
            </map>
        </property>
    </bean>

    <!-- 启动Shrio的注解 -->
    <bean id="lifecycleBeanPostProcessor"
          class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    <bean
            class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
            depends-on="lifecycleBeanPostProcessor" />
    <bean
            class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>
</beans>

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

(3) 修改web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

  <!--shiro过滤器的代理-->
<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--当tomcat启动时创建DipatcherServlet 默认当访问controller路径时创建-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

修改controller层

登录

package com.xzj.controller;

import com.xzj.entity.User;
import com.xzj.service.UserService;
import com.xzj.uitl.CommonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author xuan
 */
@Controller
public class LoginController {
    @PostMapping("/login")
    @ResponseBody
    public CommonResult login (String username, String userpwd){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,userpwd);
        try{
            subject.login(token);
            return new CommonResult(2000,"登录成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult(5000,"登录失败",null);
        }
    }
}

用户权限

package com.xzj.controller;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xuan
 */
@RestController
@RequestMapping("/user")
public class UserCotroller {
    @GetMapping("/query")
    @RequiresPermissions(value={"/user/query"})
    public String query(){
        return "user:query";
    }

    @GetMapping("/update")
    @RequiresPermissions(value={"/user/update"},logical = Logical.OR)
    public String update(){
        return "user:update";
    }

    @GetMapping("/insert")
    @RequiresPermissions(value={"/user/insert"})
    public String add(){
        return "user:insert";
    }

    @GetMapping("/delete")
    @RequiresPermissions(value={"/user/delete"})
    public String delete(){
        return "user:delete";
    }

    @GetMapping("/export")
    @RequiresPermissions(value={"/user/export"})
    public String export(){
        return "user:export";
    }
}

dao层

package com.xzj.dao;


import com.xzj.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserDao {

        @Select(value = "select * from user where username=#{username}")
        User selectByUsername(String username);

    @Select(value = "select percode from user_role ur join role_permission rp on ur.roleid=rp.roleid join permission p on  rp.perid=p.perid where ur.userid=#{userid}")
    List<String> selectByUserId(Integer userid);

    User findByUsername(String username);

    public List<String> findById(Integer userid);
}

entity层

package com.xzj.dao;


import com.xzj.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserDao {

        @Select(value = "select * from user where username=#{username}")
        User selectByUsername(String username);

    @Select(value = "select percode from user_role ur join role_permission rp on ur.roleid=rp.roleid join permission p on  rp.perid=p.perid where ur.userid=#{userid}")
    List<String> selectByUserId(Integer userid);

    User findByUsername(String username);

    public List<String> findById(Integer userid);
}

filter层

package com.xzj.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzj.uitl.CommonResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @author xuan
 */
public class LoginFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        CommonResult commonResult = new CommonResult(4001,"未登录",null);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(commonResult);
        writer.print(json);
        writer.flush();
        writer.close();
        return false;
    }
}

handler层

package com.xzj.handler;

import com.xzj.uitl.CommonResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author xuan
 */
@ControllerAdvice
public class MyException {
    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public CommonResult aunth(UnauthorizedException e){
        e.printStackTrace();
        return  new CommonResult(4002,"权限不足",null);
    }
}

realm层

package com.xzj.realm;

import com.xzj.entity.User;
import com.xzj.service.UserService;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xuan
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User) principalCollection.getPrimaryPrincipal();

        List<String> list =userService.selectByUserId(user.getUserid());
        if(list!=null&&list.size()>0){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermissions(list);
            return info;
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        String username = (String) authenticationToken.getPrincipal();
        String username = (String) authenticationToken.getPrincipal();
        User user= userService.findByUser(username);
        if(user!=null){
            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
                    user.getUserpwd(),credentialsSalt,this.getName());
            return info;
        }
        return null;
    }
}

service层

package com.xzj.service;

import com.xzj.dao.UserDao;
import com.xzj.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xuan
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    public User findByUser(String username) {
        User user = userDao.selectByUsername(username);
        return user;
    }

    public List<String> selectByUserId(Integer userid) {
        List<String> list =userDao.selectByUserId(userid);

        return list;
    }

    public List<String> findPermissionByUsername(Integer userid) {
        List<String> list =userDao.findById(userid);

        return list;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值