1.前台取数据
controller中获取数据
@RequestMapping({"/login"})
public String login(String username ,String password ,Model model){
//获取当前用户名
Subject subject = SecurityUtils.getSubject();
//封装用户的登录信息
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
//执行登录操作
subject.login(token);
return "index";
}catch (UnknownAccountException uae){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException ice){
model.addAttribute("msg","密码错误");
return "login";
}
}
2.编写认证代码
一进行登录操作,就会走Realm中的认证方法。
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证");
//数据从数据库中取
String username = "root";
String password = "123";
//获取令牌
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//信息验证
if(!userToken.getUsername().equals(username)){
return null;//抛出异常
}
//密码认证,shiro做
return new SimpleAuthenticationInfo("",password,"");
}