HybJwtRealm.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.bofeng.security;
  2. import com.bofeng.JwtHelper;
  3. import com.bofeng.service.SecurityService;
  4. import lombok.extern.slf4j.Slf4j;
  5. import lombok.val;
  6. import org.apache.shiro.authc.AuthenticationException;
  7. import org.apache.shiro.authc.AuthenticationInfo;
  8. import org.apache.shiro.authc.AuthenticationToken;
  9. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  10. import org.apache.shiro.authz.AuthorizationInfo;
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  12. import org.apache.shiro.realm.AuthorizingRealm;
  13. import org.apache.shiro.subject.PrincipalCollection;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.context.annotation.Lazy;
  16. import org.springframework.stereotype.Service;
  17. import java.util.Collection;
  18. @Service
  19. @Slf4j
  20. public class HybJwtRealm extends AuthorizingRealm {
  21. @Autowired
  22. @Lazy
  23. private SecurityService securityService;
  24. @Override
  25. public boolean supports(AuthenticationToken token) {
  26. return token instanceof JwtToken;
  27. }
  28. /**
  29. * 当需要检测用户权限的时候调用此方法
  30. * 例如 checkRole, checkPermission
  31. */
  32. @Override
  33. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  34. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  35. //用户类型,添加进角色表
  36. simpleAuthorizationInfo.addRole(JwtHelper.getUserType());
  37. //用户的 UserType 添加进 Permission
  38. simpleAuthorizationInfo.addStringPermission(JwtHelper.getUserType());
  39. return simpleAuthorizationInfo;
  40. }
  41. /**
  42. * 用户名正确与否
  43. */
  44. @Override
  45. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
  46. val jwtToken = (String) auth.getCredentials();
  47. securityService.verify(jwtToken);
  48. return new SimpleAuthenticationInfo(jwtToken, jwtToken, "HybJwtRealm");
  49. }
  50. }