折腾了好多天,遇到了好多傻逼问题。也在网上找了许多教程。对着人家源码敲都出问题,最后果断删掉之前写的代码,重新按照自己的意思来写。果然,只有自己想的才是适合自己的啊!结果就实现了认证功能。
重点:要先理解shiro的基础,我发现一个博客写的不错,可以在这看看:点击打开链接
实现环境:自己搭建的一个SSM框架下集成Shiro
流程:(当然最重要的是先要配置环境,这个自行百度吧)
1.设计数据库:一张用户信息表,最好在往数据库里添加数据的时候,密码那块用MD5+salt加密,Shiro也提供了这个加密功能, 只要不被人家发现你的salt,原则上是破解不了的。
2.编写Mybatis查询的xml文件和常见Dao接口
3.在service层实现数据查询
4.自定义一个realm,在这里实现登录认证
5.在web层实现将用户输入的账号和密码保存到Shrio的token中,并调用login()方法将数据传到AuthenticationToken
6.编写前端页面
下面开始贴代码:(只贴关于登录验证那块的代码,其余的servie层,Dao层的写法就不说了,有点mvc和框架基础的人都知道该怎么写的)
自定义的realm:实现根据token的内容往数据库查找到相应的信息,然后调用认证方法执行认证操作
public class CustomRealm extends AuthorizingRealm {
@Autowired
private ShiroUserService userService;
//登录认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username= (String) authenticationToken.getPrincipal();
User user=userService.queryUser(username);
if(user==null){
return null;
}
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),this.getName());
return simpleAuthenticationInfo;
}
//授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
web层写法:在这里将用户名和密码传到token里并执行login方法
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String login(HttpServletRequest request, Model model){
CustomException customException=null;
String username=request.getParameter("username");
String password=request.getParameter("password");
if((username!=null && password!=null)){
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
Subject subject= SecurityUtils.getSubject();
try{
subject.login(token);
}catch (AuthenticationException e){
customException=new CustomException(e.getMessage());
}
if( subject.isAuthenticated()){
subject.logout();
System.out.println("认证成功");
model.addAttribute("username",username);
return "/loginsuccess";
}else {
model.addAttribute("exception",customException.getMessage());
return "/refuse";
}
}
return "login";
}