Apache Shiro userRolesQuery只寻找一个int

时间:2016-12-08 22:23:10

标签: java security authorization shiro

我能够使用Apache Shiro进行身份验证,但现在我需要授权这意味着从数据库中获取角色。查询有效,但前提是我使用的是整数角色。由于某种原因,它正在寻找整数的角色。如果我不得不寻找数字作为角色,这似乎无益,我是否缺少一些设置告诉Shiro寻找字符串或varchar?

这是我的Shiro.ini文件:

[main]
ds = org.apache.shiro.jndi.JndiObjectFactory 
ds.requiredType = javax.sql.DataSource
ds.resourceName = jdbc/SQL05

jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.dataSource = $ds
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT company_password FROM CompanyUser where company_username = ?
jdbcRealm.userRolesQuery = SELECT role FROM CompanyUser where company_username = ?

Authentication.java

        System.setProperty("log4j.category.org.apache.shiro", "DEBUG");          
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();
        String  b = "false";
        log.info("WTF");
        try{
            if (!currentUser.isAuthenticated()) {

                UsernamePasswordToken token = new UsernamePasswordToken("user1", "test")   ;
                token.setRememberMe(true);
                try {                        
                    currentUser.login(token); 
                    b = "You have successfully logged in user: " + token.getPrincipal().toString();
                    if (currentUser.hasRole("1")) {
                        b += " and they have the role of being awesome";
                    } else {
                       b += " and we can't find the role yet.";
                    }

                }catch (UnknownAccountException uae) {
                    b =  token.getPrincipal().toString();
                    log.info("There is no user with username of " + token.getPrincipal().toString());
                } 
            }
        }catch (AuthenticationException ae) {
            b = ae.toString();
            log.info(b);
        }catch(Exception e){
            b = e.toString();
            log.info(b);
        }

所以要明确,这目前有效,因为我有:

 currentUser.hasRole("1")

在那里,角色字段的用户名为1。如果我将1更改为&#34;真棒&#34; (在没有引号的情况下)我得到以下错误:

  

严重:com.microsoft.sqlserver.jdbc.SQLServerException:转换nvarchar值时转换失败&#39; Awesome&#39;数据类型int。

那么如何让它接受字符串?

我的表公司用户:

  

userid int not null auto increment

     

personid int not null

     

company_username varchar(15)not null

     

company_password varchar(15)not

     

null role varchar(20)not null

出于某种原因,它试图转换列#34;角色&#34;到一个int。

1 个答案:

答案 0 :(得分:0)

您应该使用currentUser.hasRole("awesome")而不是currentUser.hasRole(awesome)

awesomea是变量吗?如果是这样,请举例说明。