基于ini的Shiro认证
在pom.xml文件中导入jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
编写ini配置文件:shiro.ini
#用户的身份、凭据
[users]
zhangsan=555
lisi=666
在测试类中使用ini做数据源进行认证
public void testShiro() throws Exception{
//加载 shiro.ini 配置文件,得到配置中的用户信息(账号+密码)
IniSecurityManagerFactory factory =new IniSecurityManagerFactory("classpath:shiro.ini"); //
创建 Shiro 的安全管理器
SecurityManager manager = factory.getInstance(); //
将创建的安全管理器添加到运行环境中
SecurityUtils.setSecurityManager(manager);
//获取登录的用户主体对象
Subject subject = SecurityUtils.getSubject();
System.out.println("登录前的认证状态:"+subject.isAuthenticated());//false //创建登录用户的身份凭证
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","555");
try {
//登录认证
subject.login(token);
} catch (UnknownAccountException e){
e.printStackTrace();
System.out.println("用户名错误");
} catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("密码错误");
}
System.out.println("登录后的认证状态:"+subject.isAuthenticated());
//true
}
使用自定义Realm认证
自定义Realm
- 继承与AuthorizingRealm类
- 实现两个方法(AuthenticationInfo:认证和AuthorizationInfo:授权)
- 代码示例:
//登入数据源
@Component
public class LoginRealm extends AuthorizingRealm {
//连接数据库
@Autowired
private IEmployeeService employeeService;
@Autowired
private Employee_RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
//加密登入的凭证
@Autowired
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
super.setCredentialsMatcher(credentialsMatcher);
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取传过来需要验证的用户名
String username = (String)authenticationToken.getPrincipal();
//获取该验证数据库对象
Employee employee = employeeService.checkName(username);
//判断账号是否禁用
if(employee.isStatus()){
throw new DisabledAccountException();
}
//如果有数据,就返回对象,没有就返回null
if(employee != null){
//返回一个SimpleAuthenticationInfo
//当有加密时,需要在这里加盐
return new SimpleAuthenticationInfo(employee,employee.getPassword(),
ByteSource.Util.bytes(username),"LoginRealm");
}
return null;
}
//权限
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("=======================");
//先创建一个简单Shiro权限对象
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//获取当前登入用户
//因为之前在认证信息中加入了employee对象
Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
//判断是否是admin
if(employee.isAdmin()){
info.addRole("ADMIN");
info.addStringPermission("*:*");
return info;
}
//获取该用户的所有角色,是String集合
List<Role> roleList= roleMapper.selectList(employee.getId());
ArrayList<String> roles = new ArrayList<String>();
for (Role role:roleList) {
roles.add(role.getSn());
}
//添加至权限对象中
info.addRoles(roles);
//获取权限
List<String> permissions = permissionMapper.selectByEmpId(employee.getId());
//添加至权限对象中
info.addStringPermissions(permissions);
return info;
}
配置SecurityManager中的Realm
shiro.ini
#自定义的 Realm 信息
crmRealm=cn.wolfcode.crm.shiro.CRMRealm
#将 crmRealm 设置到当前的环境中
securityManager.realms=$crmRealm
在框架中使用Shiro认证
在pom.xml添加依赖
<shiro.version>1.5.2</shiro.version>
<!--shiro 核心-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro 的 Web 模块-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro 和 Spring 集成-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro 底层使用的 ehcache 缓存-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro 依赖的日志包-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--shiro 依赖的工具包-->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!--Freemarker 的 shiro 标签库-->
<dependency>
<groupId>net.mingsoft</groupId>
<artifactId>shiro-freemarker-tags</artifactId>
<version>1.0.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
</exclusion>
</exclusions>
</dependency>
在web.xml中使用shiro过滤器
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Shiro.xml
<bean id="shiroFilter"
class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!--引用指定的安全管理器-->
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.html"/>
<property name="filterChainDefinitions">
<value>
/login.html=anon
/login.do=anon
/js/**=anon
/images/**=anon
/css/**=anon
/**=authc
</value>
</property>
</bean>
shiro有哪些过滤器
滤器的名称 | Java 类 |
---|---|
anon | org.apache.shiro.web. lter.authc.AnonymousFilter |
authc | org.apache.shiro.web. lter.authc.FormAuthenticationFilter |
authcBasic | org.apache.shiro.web. lter.authc.BasicHttpAuthenticationFilter |
roles | org.apache.shiro.web. lter.authz.RolesAuthorizationFilter |
perms | org.apache.shiro.web. lter.authz.PermissionsAuthorizationFilter |
user | org.apache.shiro.web. lter.authc.UserFilter |
logout | org.apache.shiro.web. lter.authc.LogoutFilter |
port | org.apache.shiro.web. lter.authz.PortFilter |
rest | org.apache.shiro.web. lter.authz.HttpMethodPermissionFilter |
ssl | org.apache.shiro.web. lter.authz.SslFilter |
anon: 匿名拦截器,即不需要登录即可访问;一般用于静态资源过滤;示例“/static/=anon”
authc: 表示需要认证(登录)才能使用;示例“/=authc” 主要属性:usernameParam:表单提交的用户名参数名( username);
passwordParam:表单提交的密码参数名(password);
rememberMeParam:表单提交的密码参数名(rememberMe)
loginUrl:登录页面地址(/login.jsp);
successUrl:登录成功后的默认重定向地址;
failureKeyAttribute:登录失败后错误信息存储 key(shiroLoginFailure);authcBasic: Basic HTTP 身份验证拦截器
主要属性: applicationName:弹出登录框显示的信息(application);
roles:角色授权拦截器,验证用户是否拥有资源角色;示例“/admin/=roles[admin]”
perms:权限授权拦截器,验证用户是否拥有资源权限;
Shiro安全管理器
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="crmRealm"/>
</bean>
在安全管理器中使用我们自己的Realm
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="crmRealm"/>
</bean>
网友评论