UserRealm.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.qxgmat.util.shiro;
  2. import com.qxgmat.data.dao.entity.User;
  3. import com.qxgmat.service.UsersService;
  4. import org.apache.shiro.authc.*;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  7. import org.apache.shiro.realm.AuthorizingRealm;
  8. import org.apache.shiro.subject.PrincipalCollection;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import java.util.ArrayList;
  13. /**
  14. * Created by GaoJie on 2017/11/3.
  15. */
  16. public class UserRealm extends AuthorizingRealm {
  17. private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);
  18. @Autowired
  19. private UsersService usersService;
  20. @Override
  21. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  22. String className = UserRealm.class.getName();
  23. boolean selected = false;
  24. for(String realmNames: principalCollection.getRealmNames()){
  25. if(realmNames.contains(className)) selected = true;
  26. }
  27. if(!selected) return null;
  28. ArrayList<String> roleAuthorization = new ArrayList<String>();
  29. SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
  30. roleAuthorization.add("user");
  31. sa.addRoles(roleAuthorization);
  32. return sa;
  33. }
  34. @Override
  35. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  36. UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
  37. String areaMobile = token.getUsername();
  38. String password = new String(token.getPassword());
  39. String[] info = areaMobile.split(":");
  40. if (info.length<2){
  41. throw new UnknownAccountException("手机格式错误!");
  42. }
  43. if (info[0]==null || info[0].isEmpty()) {
  44. throw new UnknownAccountException("国际码不能为空!");
  45. }
  46. if (info[1]==null || info[1].isEmpty()) {
  47. throw new UnknownAccountException("手机不能为空!");
  48. }
  49. User user = usersService.getByMobile(info[0], info[1]);
  50. if (user == null || user.getId() <= 0) {
  51. throw new UnknownAccountException("用户不存在!");
  52. }
  53. // if(!usersService.equalsPassword(user, password)){
  54. // throw new IncorrectCredentialsException("用户名或密码错误!");
  55. // }
  56. return new SimpleAuthenticationInfo(user, password, getName());
  57. }
  58. }