Shiro HelloWord

来源:互联网 发布:如何快速提高淘宝信誉 编辑:程序博客网 时间:2024/06/02 06:27
目录结构以及jar

Quickstart.java
package com.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 
/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public 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 currentUser = SecurityUtils.getSubject(); 
        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()) {
            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 (AuthenticationException ae) { 
            /// /意想不到的条件?错误呢? 
            }
        }


        //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:weild")) {
            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!");
        }


        //all done - log out!
        currentUser.logout(); 
        System.exit(0);
    }
}

log4j.properties
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
log4j.logger.org.apache=WARN
log4j.logger.org.springframework=WARN
log4j.logger.org.apache.shiro=TRACE
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]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5


运行结果: