1、Shiro认证流程
2、创建表单
<form action="${pageContext.request.contextPath}/shiro/login" method="post">
用户名:<input type="text" name="username"><br>
密 码:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
3、编写ShiroHandler
@Controller
@RequestMapping("/shiro")
public class ShiroHandler {
@RequestMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
//获取当前的Subject,调用SecurityUtils.getSubject()
Subject currentUser = SecurityUtils.getSubject();
//测试当前用户是否已经被认证,即是否已经登录
//调用Subject的isAuthenticated()
if (!currentUser.isAuthenticated()) {
//将用户名和密码封装成UsernamePasswordToken对象
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
try {
//调用Subject#login(),执行登录。能否登录成功,取决于shiro.ini配置文件中是否配了用户和密码
currentUser.login(token);
System.out.println("token:" + token.hashCode());
//没有指定的账户
}
// 所有认证时异常的父类
catch (AuthenticationException ae) {
System.out.println("登录失败," + ae.getMessage());
}
}
// return "redirect:/list.jsp";
return "success";
}
4、自定义Realm
使用认证功能 只需继承AuthenticatingRealm
//使用认证功能 AuthenticatingRealm
public class ShiroRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("doGetAuthenticationInfo:" + authenticationToken);
System.out.println(authenticationToken.hashCode());
return null;
}
}
5、发现,ShiroHandler 中的token与ShiroRealm参数的
authenticationToken为同一个对象,实际上是
currentUser.login(token); 参数传递到了ShiroRealm