欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

shiro学习

程序员文章站 2022-05-03 23:49:27
《十分钟入门》1.导入依赖 org.apache.shiro shiro-core 1.4.1...

《十分钟入门》
1.导入依赖

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

        		<!--  configure logging  -->
        		<dependency>
            			<groupId>org.slf4j</groupId>
            			<artifactId>jcl-over-slf4j</artifactId>
            			<version>1.7.21</version>
        		</dependency>
        		<dependency>
            			<groupId>org.slf4j</groupId>
            			<artifactId>slf4j-log4j12</artifactId>
            			<version>1.7.21</version>
        		</dependency>

        		<dependency>
            			<groupId>log4j</groupId>
            			<artifactId>log4j</artifactId>
            			<version>1.2.12</version>
        		</dependency>
    	</dependencies>

2.配置文件:

log4j.properties
// An highlighted block
log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

3.HelloWord:

HelloWord:
class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        //基本的得到工厂对象操作
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //获得一个Subject对象
        Subject currentUser = SecurityUtils.getSubject();

        //通过当前用户拿到Session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        //判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {
            //token  令牌
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //设置记住我
            token.setRememberMe(true);

            try {
                //进行登录操作
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //粗粒度
        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //细粒度
        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //注销
        currentUser.logout();

        //结束
        System.exit(0);
    }
}

《完整过程》
1.导入相关依赖

	  <!--  shiro整合spring  -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.0</version>
        </dependency>

        <!--  shiro整合mybatis  -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

2.写config类(spring环境已经搭建好了)

(1)Realm类
/**
 		* 自定义的Realm类,继承AuthorizingRealm
 		*/
		public class UserRealm extends AuthorizingRealm {

    			@Autowired
    			private AccountServiceImpl accountService;

   			 /**
     			* 授权
     			* @param principalCollection
     			* @return
     			*/
    			@Override
    			protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        				System.out.println("执行了--->授权方法");

        				//拿到当前登录的对象
        				Subject subject = SecurityUtils.getSubject();
        				Account currentAccount = (Account) subject.getPrincipal();

        				//授权信息
        				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        				//将数据库中的权限信息赋值给当前信息
        				info.addStringPermission(currentAccount.getPerms());

        				return info;
   			 }

    			/**
     			* 认证
    			 * @param token
     			* @return
     			* @throws AuthenticationException
     			*/
    			@Override
    			protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        				System.out.println("执行了--->认证方法");

       		 		UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        				//从数据库中获取数据
        				Account account = accountService.findAccountByName(userToken.getUsername());

        				//判断数据库中是否有当前对象,没有的话抛出异常,UnknownAccountException
        				if (account == null){
            					return null;
        				}

        				//密码认证
        				return new SimpleAuthenticationInfo(account,account.getPassword(),"");
    			}
		}
(2)ShiroConfig:
@Configuration
public class ShiroConfig {

    /**
     * 3.shiro过滤器工厂,ShiroFilterFactoryBean
     * @param defaultWebSecurityManager     安全管理器
     * @return                              过滤器工厂
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        //实例化工厂对象
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        /**
         * 添加shiro的内置过滤器
         * anon:    无需认证就可以访问
         * authc:   必须认证了才可以访问
         * user:    必须有记住我才可以用(不常用)
         * perms:   拥有对某个资源的权限才能访问
         * role:    拥有某个角色权限才能访问
         */
        //拦截
        Map<String,String> filterMap = new LinkedHashMap<>();

        //授权,没有授权会跳转到未授权页面。
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        filterMap.put("/user/*","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");

        return shiroFilterFactoryBean;
    }

    /**
     * 2.DefaultWebSecurityManager
     * @param userRealm                     realm对象
     * @return                              安全管理器
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        //实例化安全管理器对象
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //关联Realm
        securityManager.setRealm(userRealm);

        return securityManager;
    }

    /**
     * 1.创建realm对象,自定义类,继承AuthorizingRealm
     * realm对象
     * @return                              realm对象
     */
    @Bean(name="userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

本文地址:https://blog.csdn.net/zmm__1377445292/article/details/109526158