SSM整合shiro

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

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

(12条消息) Web开发_lqh12138的博客-CSDN博客

(2)ssm整合到web工程

(12条消息) SSM整合_lqh12138的博客-CSDN博客

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配置文件

<!--整合shiro的配置内容-->
 <!--①SecurityManager-->
 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
       <property name="realm" ref="realm"/>
 </bean>
 <!--创建自定义realm类对象-->
 <bean id="realm" class="com.ykq.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="loginUrl" value="/login.jsp"/>
      <!--没有权限,跳转的路径-->
      <property name="unauthorizedUrl" value="/unauthorized.jsp"/>

      <property name="filterChainDefinitions">
            <value>
                 /login=anon
                 /**=authc
            </value>
      </property>
 </bean>

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

 修改web.xml文件

 <!--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>

修改controller层

@PostMapping("/login")
 public String login(String username,String password){
     Subject subject = SecurityUtils.getSubject();
     UsernamePasswordToken token=new UsernamePasswordToken(username,password);
     try {
         subject.login(token);
         return "redirect:/success.jsp";
     }catch (Exception e){
         return "redirect:/login.jsp";
     }
 }

用户权限

package com.lqh.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;
 

@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.lqh.dao;
 
 
import com.lqh.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.lqh.dao;
 
 
import com.lqh.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.lqh.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;
 

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.lqh.handler;
 
import com.lqh.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;
 

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

realm层

package com.lqh.realm;
 
import com.lqh.entity.User;
import com.lqh.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;
 

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.lqh.service;
 
import com.lqh.dao.UserDao;
import com.lqh.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
 

@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、付费专栏及课程。

余额充值