Shiro数据库获取数据

1.添加环境

<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.3.RELEASEversion>
dependency>

2.添加相关配置文件
(1)spring-jdbc.xml


<beanclass="com.alibaba.druid.pool.DruidDataSource"id="dataSource">
<propertyname="url"value="jdbc:mysql://localhost:3306/shiro_test?serverTimezone=UTC"/>
<propertyname="username"value="root"/>
<propertyname="password"value="root"/>
bean>

<beanclass="org.springframework.jdbc.core.JdbcTemplate"id="jdbcTemplate">
<propertyname="dataSource"ref="dataSource"/>
bean>

3.自定义realm重写用户认证及权限认证方法

Publicclass MyRealm extends AuthorizingRealm{
@Resource
Private UserDao userDao;
@Override
Protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
//根据用户名获取相关角色以及权限
Stringusername=(String)principalCollection.getPrimaryPrincipal();
Stringrole=userDao.getRoleByUsername(username);
Setroles=newHashSet();
roles.add(role);
SimpleAuthorizationInfo simpleAuthorizationInfo=newSimpleAuthorizationInfo();
simpleAuthorizationInfo.setRoles(roles);
Return simpleAuthorizationInfo;
}
@Override
Protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)throws AuthenticationException{
/*自定义realm验证用户名和密码*/
Stringusername=(String)authenticationToken.getPrincipal();
Stringpassword=newString((char[])authenticationToken.getCredentials());
Useruser=userDao.getUserPassword(username);
if(user!=null){
if(!user.getPassword().equals(password)){
System.out.println("用户密码错误");
Throw new IncorrectCredentialsException();
}
}else{
System.out.println("用户不存在");
Throw new UnknownAccountException();
}
Return new SimpleAuthenticationInfo(username,password,getName());
}
}

你可能感兴趣的:(shiro)