从零开始手写Tomcat的教程10节---安全性

x33g5p2x  于2022-03-17 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(495)

对tomcat中管道和阀门机制不懂的小伙伴,参考本篇文章

领域

目前可知结构,如图所示,下面继续分析

GenericPrincipal类

LoginConfig类

Authenticator接口

在Tomcat中的*Base类基本都是实现了接口中大部分方法的基础类,将会有不同实现需求的少量方法设置为抽象方法,让不同的子类实现,大家可以学习这种设计思想、

BasicAuthenticator的authenticate方法

  1. public boolean authenticate(HttpRequest request,
  2. HttpResponse response,
  3. LoginConfig config)
  4. throws IOException {
  5. // Have we already authenticated someone?
  6. Principal principal =
  7. ((HttpServletRequest) request.getRequest()).getUserPrincipal();
  8. if (principal != null) {
  9. if (debug >= 1)
  10. log("Already authenticated '" + principal.getName() + "'");
  11. return (true);
  12. }
  13. // Validate any credentials already included with this request
  14. HttpServletRequest hreq =
  15. (HttpServletRequest) request.getRequest();
  16. HttpServletResponse hres =
  17. (HttpServletResponse) response.getResponse();
  18. String authorization = request.getAuthorization();
  19. String username = parseUsername(authorization);
  20. String password = parsePassword(authorization);
  21. principal = context.getRealm().authenticate(username, password);
  22. if (principal != null) {
  23. register(request, response, principal, Constants.BASIC_METHOD,
  24. username, password);
  25. return (true);
  26. }
  27. // Send an "unauthorized" response and an appropriate challenge
  28. String realmName = config.getRealmName();
  29. if (realmName == null)
  30. realmName = hreq.getServerName() + ":" + hreq.getServerPort();
  31. // if (debug >= 1)
  32. // log("Challenging for realm '" + realmName + "'");
  33. hres.setHeader("WWW-Authenticate",
  34. "Basic realm=\"" + realmName + "\"");
  35. hres.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  36. // hres.flushBuffer();
  37. return (false);
  38. }

安装验证器阀

应用程序

SimpleContextConfig类

SimpleRealm类

SimpleUserDataBaseRealm类

Bootstarp1类

BootStrap2类

总结

  • Principal主要是为了对用户的一些属性进行封装,所以也被称为主体对象,这里主体指的是用户,主要封装了用户姓名,密码,用户角色,当前关联的领域对象realm
  • realm主要负责完成认证功能,然后tomcat中一个Context容器关联一个Realm对象,并且不同的realm子类实现,通过不同的方式来加载有效用户信息,在authenticate方法中,对传入用户名密码进行验证,然后生成一个 Principal对象返回
  • AuthenticatorBase类主要按照实现的认证方式不同,采取不同的认证流程,但是对用户信息校验,都是调用realm的认证方法完成的,这也算是一种解耦,因为用户信息的读取有多种不同的方式

从tomcat的设计中,我们还可以思考一下rcpc权限管理框架设计的一种思想:

由于本人其实对于tomcat的安全这块没有做深入了解,上面写的内容可能会有偏差,包括个人的理解方面,可能也会有问题,但是我这里更想介绍的是tomcat中权限与安全管理给我的一种启发和思考

相关文章