shiro学习笔记

1 、Shiro 三大核心对象

  1. Subject:其实是当前正在执行的用户对象
  2. SecurityManager:管理所有对象
  3. Realms:连接数据

2 依赖

Shiro的依赖

		<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>

Shrio和Spring的整合依赖

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

3 配置过滤器

@Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        /*
            添加Shiro内置过滤器,常用的有如下过滤器:
                anon:无需认证就可以访问
                authc:必须认证了才能访问
                user:必须拥有rememberMe才能用
                perms:拥有对某个资源的权限才能用
                role:拥有某个角色权限
         */
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        filterChainDefinitionMap.put("/user/add", "authc");
        filterChainDefinitionMap.put("/user/update", "authc");

        // 支持通配符的方式
//        filterChainDefinitionMap.put("/user/*", "authc");

        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        // 设置登录请求
        bean.setLoginUrl("/toLogin");

        return bean;
    }

4 自定义UserRealm

public class UserRealm extends AuthorizingRealm {

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("============执行授权============");
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("============执行认证============");

        // 用户名,密码  实际应该是从数据库中取
        String username = "root";
        String password = "root";
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        if (!usernamePasswordToken.getUsername().equals(username)) {
            return null; // 抛出异常 UnknownAccountException
        }

        // 密码认证
        return new SimpleAuthenticationInfo("", password, "");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值