Shiro

1.引入依赖包

        <!-- shiro依赖-->
        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.5.3</version>
        </dependency>

2.自定义realm

ublic class MyRealm extends AuthorizingRealm {


    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //使用用户名获取权限
        List<TbPermission> byUserName = permissionMapper.findByUserName(name);
        Set set=new HashSet<>();
        for (TbPermission tb:byUserName){
            set.add(tb.getTitle());
        }
       //将权限设置到AuthorizationInfo 中
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
         //将数据库查询出的权限设置到权限管理器中
        simpleAuthorizationInfo.addStringPermissions(set);
        //还可添加角色
        simpleAuthorizationInfo.addRole(传入参数);
        return simpleAuthorizationInfo;
    }
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取到前端传入的用户名
        String name = (String) authenticationToken.getPrincipal();
        TbUser byUserName = userRepository.findByUserName(name);
        if (byUserName!=null) {
            //将数据库正确密码交给shiro
            return new SimpleAuthenticationInfo(name, byUserName.getUserPassword(), ByteSource.Util.bytes(name),this.getName());
        }
        return null;
    }

}

3.service层

@Service
public class UserServiceImpl implements UserService {

   
    @Override
    public String login(TbUser tbUser) {
        //从secrityManage中的SecurityUtils  获取到登录主体
        Subject subject = SecurityUtils.getSubject();
        //设置前端的用户名以及密码
        UsernamePasswordToken token = new UsernamePasswordToken(tbUser.getUserName(), tbUser.getPassword());
       try {
           //使用主体登录
           subject.login(token);
       }catch (IncorrectCredentialsException e){
           return "密码错误";
       }catch (UnknownAccountException e){
           return "用户名不存在";
       }

       //验证用户是否登录
       if (subject.isAuthenticated()){
           //放置在session中
           return "登录成功";
       }

        return "登录失败";
    }
}

4.shrio与spring整合

@Configuration
public class ShiroConfig {

    //3.跟springboot整合
    @Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        //声明shiro过滤器
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //将SecurityManager 核心设置到过滤器中
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }
    //开启自动代理类对象
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    //开启shiro的注解模式
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        //defaultWebSecurityManager.
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
        return authorizationAttributeSourceAdvisor;
    }


    //2.默认的安全管理器,将自定义的Realm配置到SecurityManager中
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("realm")MyRealm myRealm){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //将myRealm设置到 defaultWebSecurityManager 核心中
        defaultWebSecurityManager.setRealm(myRealm);
        return defaultWebSecurityManager;
    }

    //1.配置Realm
    @Bean(name = "realm")
    public MyRealm myRealm(@Qualifier("hashedCredentialsMatcher")HashedCredentialsMatcher                         hashedCredentialsMatcher){
        MyRealm myRealm = new MyRealm();
        //关闭shiro自己的比对密码的方式
        myRealm.setAuthenticationCachingEnabled(false);
        //设置自定义的加密的方式(MD5加密进行注入)
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return myRealm;
    }

    //配置MD5加密
    /**
     * MD5加密
     * @return
     */
    @Bean(name = "hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式为MD5
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        hashedCredentialsMatcher.setHashIterations(1024);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }
}

5.设置异常捕捉类

//@ControllerAdvice 控制器增强,所有controller发生异常后都会进行捕捉
@ControllerAdvice
@ResponseBody
public class ExceptionController {

    //未登录异常
    @ExceptionHandler(AuthenticationException.class)
    public Base nologin(){
        return new Base(1,"用户未登录",null,null);
    }
    //没有权限异常
    @ExceptionHandler(AuthorizationException.class)
    public Base auth(){

        return new Base(1,"该用户没有权限,请充值",null,null);
    }

}

6.controller层(请求方法上)加入权限注解:@RequiresPermissions("findAll")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值