搭建springboot项目,引入以下依赖:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--shiro--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.2</version></dependency></dependencies>
一、身份验证:
1、登录/退出:
(1)数据mock:新建shiro-user.ini文件
[users]
zs=123
ls=123
admin=123
(2)单元测试:
import com.demo.shiro.ShiroApplication;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;/*** 身份验证*/
@SpringBootTest(classes = {ShiroApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class ShiroAuthenticationTest {/*** 1、登陆/退出,以admin/123用户为例*/@Testpublic void testLoginInAndPut(){//1、创建SecurityManagerFactory,用户名/密码硬编码在ini文件,实际应存储在数据库并将密码加密IniSecurityManagerFactory factory=new IniSecurityManagerFactory("classpath:shiro-user.ini");//2、创建安全管理器SecurityManager,并绑定给SecurityUtilSecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);//3、通过SecurityUtil获取登入用户主体subject,并创建tokenSubject subject = SecurityUtils.getSubject();UsernamePasswordToken token=new UsernamePasswordToken("admin", "123");//用户认证(shrio的核心功能之一)try {//异常//4、登录,即身份验证subject.login(token);System.out.println("认证成功");} catch (AuthenticationException e) {//5、认证失败//org.apache.shiro.authc.UnknownAccountException:账号错误异常//org.apache.shiro.authc.IncorrectCredentialsException:密码错误异常//org.apache.shiro.authz.UnauthorizedException: 授权错误异常System.out.println("认证失败");e.printStackTrace();}//6、安全退出subject.logout();}
}
执行,控制台输出:认证成功;
将密码改为123456,抛出密码错误异常
如上代码可总结出身份验证的步骤:
1)收集用户身份 / 凭证,即如用户名 / 密码;
2)调用 Subject.login 进行登录,如果失败将得到相应的 AuthenticationException 异常,根据异常提示用户错误信息;否则登录成功;
3)最后调用 Subject.logout 进行退出操作。
二、角色验证: