shiro整合springboot

shiro整合流程示意图

在这里插入图片描述

常见过滤器

在这里插入图片描述

shiro注解
@RequiresRoles(value={"admin","user"})//同时具有相同角色
@RequiresPermissions("user:update:*")//判断权限字符串

在这里插入图片描述

shiroConfig类
import com.wj.shiro.shirobag.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

public class ShiroConfig {
    //1、创建shiroFilter(负责拦截所有请求)
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源、系统公共资源
        Map<String,String> map = new HashMap<>();
        map.put("/index","authc");//authc请求这个资源需要认证和授权
        map.put("/login","anon");//anon 设置为公共资源

        //默认认证界面路径
        bean.setLoginUrl("/login.html");
        bean.setFilterChainDefinitionMap(map);

        return bean;
    }
    //2、创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        //给安全管理器设置Realm
        manager.setRealm(realm);
        return manager;
    }
    //3、创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        matcher.setHashAlgorithmName("MD5");
        //设置散列次数
        matcher.setHashIterations(1024);
        return customerRealm;
    }
}

随机盐函数
import java.util.Random;

public class SaltUtils {
    public static String getSalt(int n){
        char[] chars = "111222333444555666#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length-1)];
            sb.append(aChar);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String salt = getSalt(3);
        System.out.println(salt);
    }
}
Controller示例
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {

    //退出登录
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequestMapping("login")
    public String login(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "index.html";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名出错");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码出错");
        }
        return "login.html";
    }
}

自定义realm
import com.wj.shiro.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 org.springframework.util.ObjectUtils;

public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String principal = (String) principals.getPrimaryPrincipal();
        //根据主身份信息获取角色和权限信息
        if ("111".equals(principal)){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermission("user:find:*");
            info.addRole("user");
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String p = (String) token.getPrincipal();
        //数据库查询,返回结果与身份信息对比
        User user = userService.findUserName(p);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo("name",
                    "pwd",
                    ByteSource.Util.bytes("salt"),
                    this.getName());
        }
        return null;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值