shiro-JdbcRealm
16552 ワード
shiro-JdbcRealm
1、加入依存
2、テスト
1、加入依存
<dependencies>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.8.1version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>1.7.25version>
<scope>compilescope>
dependency>
dependencies>
2、テスト
public void test() {
// druid
DruidDataSource dataSource=new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("240010");
// realm
JdbcRealm jdbcRealm=new JdbcRealm();
jdbcRealm.setPermissionsLookupEnabled(true);
jdbcRealm.setDataSource(dataSource);
//securityManager realm
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(jdbcRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager);
//getSubject token
Subject ssub = SecurityUtils.getSubject();
UsernamePasswordToken toke = new UsernamePasswordToken("zhangsan", "123");
// login isAuthenticated isPermitted
try {
ssub.login(toke);
if(ssub.isAuthenticated()){
System.out.println(" ");
}
if(ssub.isPermitted("userList")){
System.out.println(" userList ");
}else{
System.out.println(" userList ");
}
} catch (UnknownAccountException uae) {
System.out.println(uae.getMessage());
uae.printStackTrace();
} catch (IncorrectCredentialsException ice) {
System.out.println(ice.getMessage());
ice.printStackTrace();
}
}