shiro访问MYSQL

ChengMinglei 发布于 2011/08/03 14:26
阅读 2K+
收藏 3
如何用shiro的方法从MYSQL中获取用户信息并且进行身份验证。
加载中
0
0
cwledit
cwledit
可以看 springside3的例子..也可以看下官方的simple
0
cwledit
cwledit
public class ShiroDbRealm extends AuthorizingRealm { 

    private AccountManager accountManager; 

    /** 
     * 认证回调函数,登录时调用. 
     */ 
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { 
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken; 
        User user = accountManager.findUserByLoginName(token.getUsername()); 
        if (user != null) { 
            return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(), getName()); 
        } else { 
            return null; 
        } 
    } 

    /** 
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. 
     */ 
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
        String loginName = (String) principals.fromRealm(getName()).iterator().next(); 
        User user = accountManager.findUserByLoginName(loginName); 
        if (user != null) { 
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 
            for (Group group : user.getGroupList()) { 
                info.addStringPermissions(group.getPermissionList()); 
            } 
            return info; 
        } else { 
            return null; 
        } 
    } 

    /** 
     * 更新用户授权信息缓存. 
     */ 
    public void clearCachedAuthorizationInfo(String principal) { 
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); 
        clearCachedAuthorizationInfo(principals); 
    } 

    /** 
     * 清除所有用户授权信息缓存. 
     */ 
    public void clearAllCachedAuthorizationInfo() { 
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache(); 
        if (cache != null) { 
            for (Object key : cache.keys()) { 
                cache.remove(key); 
            } 
        } 
    } 

    @Autowired 
    public void setAccountManager(AccountManager accountManager) { 
        this.accountManager = accountManager; 
    } 
} 

0
C
ChengMinglei

引用来自“祝靖俊”的答案

重写Realm
很感谢,我自己看了一下jdbcrealm的代码还是不太会重写
0
C
ChengMinglei

引用来自“cwledit”的答案

public class ShiroDbRealm extends AuthorizingRealm { 

    private AccountManager accountManager; 

    /** 
     * 认证回调函数,登录时调用. 
     */ 
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { 
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken; 
        User user = accountManager.findUserByLoginName(token.getUsername()); 
        if (user != null) { 
            return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(), getName()); 
        } else { 
            return null; 
        } 
    } 

    /** 
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. 
     */ 
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
        String loginName = (String) principals.fromRealm(getName()).iterator().next(); 
        User user = accountManager.findUserByLoginName(loginName); 
        if (user != null) { 
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 
            for (Group group : user.getGroupList()) { 
                info.addStringPermissions(group.getPermissionList()); 
            } 
            return info; 
        } else { 
            return null; 
        } 
    } 

    /** 
     * 更新用户授权信息缓存. 
     */ 
    public void clearCachedAuthorizationInfo(String principal) { 
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); 
        clearCachedAuthorizationInfo(principals); 
    } 

    /** 
     * 清除所有用户授权信息缓存. 
     */ 
    public void clearAllCachedAuthorizationInfo() { 
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache(); 
        if (cache != null) { 
            for (Object key : cache.keys()) { 
                cache.remove(key); 
            } 
        } 
    } 

    @Autowired 
    public void setAccountManager(AccountManager accountManager) { 
        this.accountManager = accountManager; 
    } 
} 

很感谢你能为我解答,但是我没看懂哪一块是从数据库中获取信息并进行和当前信息验证。这个是我刚刚试验成功的代码

package testshiro;

 

//import java.sql.Connection;

 

//import javax.naming.InitialContext;

//import javax.naming.NamingException;

//import javax.sql.DataSource;

 

//import org.slf4j.Logger;

//import org.slf4j.LoggerFactory;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.*;

//import org.apache.shiro.config.IniSecurityManagerFactory;

import org.apache.shiro.mgt.DefaultSecurityManager;

//import org.apache.shiro.mgt.SecurityManager;

import org.apache.shiro.realm.jdbc.JdbcRealm;

//import org.apache.shiro.session.Session;

import org.apache.shiro.subject.Subject;

//import org.apache.shiro.util.Factory;

 

import com.mysql.jdbc.jdbc2.optional.*;;

 

public class Test{

 

/**

* @param args

*/

//    public Test() {

//        super();

//

//        //get the DataSource that JSecurity's JdbcRealm

//        //should use to find the user's password

//        //using the provided username

//        //see context.xml for this DataSource's properties

//        InitialContext ic;

//        DataSource dataSource;

//        try {

//

//                ic = new InitialContext();

//                dataSource = (DataSource) ic.lookup("jdbc:mysql://localhost:3306/metadata_submit");

//                this.setDataSource(dataSource);

//

//        } catch (NamingException e) {

//

//                e.printStackTrace();

//        }

//

//    }

//

//

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

public static void main(String[] args) {

// TODO Auto-generated method stub

//Logger log = Logger.getLogger(Test.class);

System.out.println("Hello shiro!");

MysqlDataSource datasource = new MysqlDataSource();

datasource.setUser("root");

datasource.setPassword("root");

datasource.setServerName("localhost");

// datasource.setDriverClassName("com.mysql.jdbc.Driver");

datasource.setUrl("jdbc:mysql://localhost:3306/metadata_submit");

// datasource.setMaxActive(10);

org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new  JdbcRealm();

jdbcRealm.setDataSource(datasource);

jdbcRealm.setPermissionsLookupEnabled(true);

jdbcRealm.setAuthenticationQuery("SELECT password FROM users WHERE username = ?");

jdbcRealm.setUserRolesQuery("SELECT role_name FROM role_name WHERE username = ?");

jdbcRealm.setPermissionsQuery("SELECT permission FROM roles_permissions WHERE role_name = ?");

 

DefaultSecurityManager security = new DefaultSecurityManager(jdbcRealm);

SecurityUtils.setSecurityManager(security);

// Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

//        SecurityManager securityManager = factory.getInstance();

//        SecurityUtils.setSecurityManager(securityManager);

 

 

        // get the currently executing user:

        Subject currentUser = SecurityUtils.getSubject();

 

 

        // Do some stuff with a Session (no need for a web or EJB container!!!)

//        Session session = currentUser.getSession();

//        session.setAttribute("someKey", "aValue");

//        String value = (String) session.getAttribute("someKey");

//        if (value.equals("aValue")) {

//            System.out.println("Retrieved the correct value! [" + value + "]");

//        }

 

        // let's login the current user so we can check against roles and permissions:

        if (!currentUser.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken("root", "123");

            token.setRememberMe(true);

           

            try {

                currentUser.login(token); 

                System.out.println("login successfully");

            } catch (UnknownAccountException uae) {

                System.out.println("There is no user with username of " + token.getPrincipal());

            } catch (IncorrectCredentialsException ice) {

                System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");

            } catch (LockedAccountException lae) {

                System.out.println("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):

        System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

 

        //test a role:

        if (currentUser.hasRole("guanliyuan")) {

            System.out.println("May the guanliyuan be with you!");

        } else {

            System.out.println("Hello, mere mortal.");

        }

 

        //test a typed permission (not instance-level)

        if (currentUser.isPermitted("lightsaber:weild")) {

            System.out.println("You may use a lightsaber ring.  Use it wisely.");

        } else {

            System.out.println("Sorry, lightsaber rings are for schwartz masters only.");

        }

 

        //a (very powerful) Instance Level permission:

        if (currentUser.isPermitted("winnebago:drive:eagle5")) {

            System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +

                    "Here are the keys - have fun!");

        } else {

            System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");

        }

 

        //all done - log out!

        currentUser.logout();

 

}

 

}


0
祝靖俊
可以加我Q:315798188
0
cwledit
cwledit

最简单的你去下个springside3的代码,SVN地址

http://springside.googlecode.com/svn/springside4/trunk/examples/mini-web

里面有完整的例子

JavaHouse
JavaHouse
这个springside4已经迁移到 http://github.com/springside/springside4/wiki
0
C
ChengMinglei

引用来自“cwledit”的答案

最简单的你去下个springside3的代码,SVN地址

http://springside.googlecode.com/svn/springside4/trunk/examples/mini-web

里面有完整的例子

这个例子是用maven写的么,我不会maven啊
0
C
ChengMinglei

引用来自“祝靖俊”的答案

可以加我Q:315798188
这个你要我回答你额名字啊,你加我吧谢谢啊,20531694
返回顶部
顶部