Commit 46e0834c084b9ca509f53608f042033941195159

Authored by fangcheng
1 parent 78ca17eb53
Exists in master

hospital模块添加shiro验证

Showing 6 changed files with 216 additions and 14 deletions

parent/center.manager/src/main/resources/dev/redis.properties View file @ 46e0834
... ... @@ -32,6 +32,6 @@
32 32 redis.maxActive=600
33 33 redis.maxWait=1000
34 34 redis.testOnBorrow=true
35   -redis.HttpSession.redisNamespace=hospital.mac
  35 +redis.HttpSession.redisNamespace=center
36 36 spring.redis.cluster.max-redirects= 3
parent/hospital.web/src/main/java/com/lyms/hospital/controller/LoginController.java View file @ 46e0834
... ... @@ -6,6 +6,13 @@
6 6 import javax.servlet.http.HttpServletResponse;
7 7  
8 8 import org.apache.commons.lang3.StringUtils;
  9 +import org.apache.shiro.SecurityUtils;
  10 +import org.apache.shiro.authc.AccountException;
  11 +import org.apache.shiro.authc.AuthenticationException;
  12 +import org.apache.shiro.authc.AuthenticationToken;
  13 +import org.apache.shiro.authc.LockedAccountException;
  14 +import org.apache.shiro.authc.UnknownAccountException;
  15 +import org.apache.shiro.authc.UsernamePasswordToken;
9 16 import org.springframework.beans.factory.annotation.Autowired;
10 17 import org.springframework.web.bind.annotation.RequestBody;
11 18 import org.springframework.web.bind.annotation.RequestMapping;
12 19  
... ... @@ -14,7 +21,9 @@
14 21 import org.springframework.web.bind.annotation.ResponseBody;
15 22 import org.springframework.web.bind.annotation.RestController;
16 23  
  24 +import com.alibaba.druid.support.json.JSONUtils;
17 25 import com.alibaba.fastjson.JSON;
  26 +import com.alibaba.fastjson.JSONObject;
18 27 import com.lyms.annotation.TokenRequired;
19 28 import com.lyms.base.common.entity.organ.Organizations;
20 29 import com.lyms.base.common.entity.role.Permissions;
21 30  
... ... @@ -26,9 +35,11 @@
26 35 import com.lyms.base.common.service.user.UsersService;
27 36 import com.lyms.constants.Constants;
28 37 import com.lyms.hospital.service.token.TokenService;
  38 +import com.lyms.shiro.ShiroWebUtils;
29 39 import com.lyms.util.DateTimeUtils;
30 40 import com.lyms.util.InstanceUtils;
31 41 import com.lyms.util.MD5Utils;
  42 +import com.lyms.util.StrUtils;
32 43 import com.lyms.web.bean.AjaxResult;
33 44 import com.lyms.web.controller.BaseController;
34 45  
35 46  
36 47  
... ... @@ -106,24 +117,29 @@
106 117 @RequestParam(value = "password", required = false) String password,
107 118 AjaxResult ajaxResult,
108 119 HttpServletResponse response) {
  120 + System.out.println("ShiroWebUtils.getCurrentUser()="+JSONObject.toJSONString(ShiroWebUtils.getCurrentUser()));
109 121 ajaxResult.setSuccess(false);
110 122 if (StringUtils.isEmpty(account) && (StringUtils.isEmpty(code) || StringUtils.isEmpty(password))) {
111 123 ajaxResult.setMessage("登录账户或者验证码为空,请输入!");
112 124 return ajaxResult;
113 125 }
114   - Users users = usersService.getUserByUsername(account);
115   - if(users == null){
116   - ajaxResult.setMessage("用户不存在!");
117   - return ajaxResult;
  126 + AuthenticationToken authenticationToken = new UsernamePasswordToken(account, password);
  127 + try {
  128 + // 查看ShiroRealm.class
  129 + SecurityUtils.getSubject().login(authenticationToken);
  130 + } catch (AuthenticationException e) {
  131 + if (e instanceof UnknownAccountException) {
  132 + ajaxResult.setMessage("用户不存在!");
  133 + return ajaxResult;
  134 + } else if (e instanceof AccountException) {
  135 + ajaxResult.setMessage("密码不正确!");
  136 + return ajaxResult;
  137 + } else if (e instanceof LockedAccountException) {
  138 + ajaxResult.setMessage("用户被禁用!");
  139 + return ajaxResult;
  140 + }
118 141 }
119   - if(!users.getPwd().equals(MD5Utils.md5(password))){
120   - ajaxResult.setMessage("密码不正确!");
121   - return ajaxResult;
122   - }
123   - if(users.getEnable() < 1){
124   - ajaxResult.setMessage("用户被禁用!");
125   - return ajaxResult;
126   - }
  142 + Users users = ShiroWebUtils.getCurrentUser();
127 143 //Organizations organizations = organizationsService.selectById( users.getOrgId());
128 144 Map<String, Object> result = InstanceUtils.newHashMap();
129 145 String token = tokenService.createToken(users);
parent/hospital.web/src/main/java/com/lyms/hospital/shiro/ShiroRealm.java View file @ 46e0834
  1 +package com.lyms.hospital.shiro;
  2 +
  3 +import java.util.HashSet;
  4 +import java.util.List;
  5 +
  6 +import org.apache.shiro.authc.AccountException;
  7 +import org.apache.shiro.authc.AuthenticationException;
  8 +import org.apache.shiro.authc.AuthenticationInfo;
  9 +import org.apache.shiro.authc.AuthenticationToken;
  10 +import org.apache.shiro.authc.LockedAccountException;
  11 +import org.apache.shiro.authc.SimpleAuthenticationInfo;
  12 +import org.apache.shiro.authc.UsernamePasswordToken;
  13 +import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
  14 +import org.apache.shiro.authz.AuthorizationInfo;
  15 +import org.apache.shiro.authz.SimpleAuthorizationInfo;
  16 +import org.apache.shiro.realm.AuthorizingRealm;
  17 +import org.apache.shiro.subject.PrincipalCollection;
  18 +import org.slf4j.Logger;
  19 +import org.slf4j.LoggerFactory;
  20 +import org.springframework.beans.factory.annotation.Autowired;
  21 +
  22 +import com.lyms.base.common.entity.user.Users;
  23 +import com.lyms.base.common.enums.StatusEnum;
  24 +import com.lyms.base.common.service.role.PermissionsService;
  25 +import com.lyms.base.common.service.user.UsersService;
  26 +import com.lyms.shiro.ShiroWebUtils;
  27 +import com.lyms.util.CollectionUtils;
  28 +import com.lyms.util.MD5Utils;
  29 +import com.lyms.util.StrUtils;
  30 +
  31 +/**
  32 + * <li>@ClassName: ShiroRealm
  33 + * <li>@Description: 自定义Realm授权与验证实现
  34 + * <li>@author 方承
  35 + * <li>@date 2015年12月29日
  36 + * <li>
  37 + */
  38 +public class ShiroRealm extends AuthorizingRealm {
  39 +
  40 + @SuppressWarnings("unused")
  41 + private static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
  42 +
  43 + public ShiroRealm() {
  44 + super(new AllowAllCredentialsMatcher());
  45 + setAuthenticationTokenClass(UsernamePasswordToken.class);
  46 + // FIXME: 暂时禁用Cache
  47 + setCachingEnabled(false);
  48 + }
  49 +
  50 + @Autowired
  51 + private UsersService sysUsersService;
  52 +
  53 + private PermissionsService sysPermissionsService;
  54 +
  55 + // @Autowired
  56 + // private ResourceService resourceService;
  57 +
  58 + @Override
  59 + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  60 + String username = (String) principals.getPrimaryPrincipal();
  61 + Users user = sysUsersService.getUserByUsername(username);
  62 + // 授权
  63 + SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  64 + List<String> roleIdList = sysUsersService.getRoleIdListByUserid(user.getId());
  65 + if (CollectionUtils.isNotEmpty(roleIdList)) {
  66 + authorizationInfo.setRoles(new HashSet<String>(roleIdList));
  67 + }
  68 + authorizationInfo.setStringPermissions(sysPermissionsService.getUserPermissionSet(user.getId(),"1"));
  69 + return authorizationInfo;
  70 + }
  71 +
  72 + @Override
  73 + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
  74 + throws AuthenticationException {
  75 + UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
  76 + String username = token.getUsername();
  77 + Users user = sysUsersService.getUserByUsername(username);
  78 + if (StatusEnum.isDisEnabled(user.getEnable())) {
  79 + throw new LockedAccountException("用户已经被禁用,请联系管理员!");
  80 + }
  81 + StringBuilder pwd = new StringBuilder(100);
  82 + for (int i = 0; i < token.getPassword().length; i++) {
  83 + pwd.append(token.getPassword()[i]);
  84 + }
  85 + if (!StrUtils.equals(user.getPwd(), MD5Utils.md5(pwd.toString()))) {
  86 + throw new AccountException("用户名密码不一致");
  87 + }
  88 + ShiroWebUtils.saveCurrentUser(user);
  89 + AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, pwd.toString(), username);
  90 + return authcInfo;
  91 + // User user = userService.getUserByUserName(username);
  92 + // if (user == null) {
  93 + // throw new UnknownAccountException("未知用户");
  94 + // }
  95 + // StringBuilder pwd = new StringBuilder(100);
  96 + // for (int i = 0; i < token.getPassword().length; i++) {
  97 + // pwd.append(token.getPassword()[i]);
  98 + // }
  99 + // if (!StrUtils.equals(user.getPassword(),
  100 + // HashUtils.md5(pwd.toString()))) {
  101 + // throw new AccountException("用户名密码不一致");
  102 + // }
  103 + // ShiroWebUtils.saveCurrentUser(user);
  104 + // AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username,
  105 + // pwd.toString(), username);
  106 + // return authcInfo;
  107 + }
  108 +
  109 +}
parent/hospital.web/src/main/resources/dev/redis.properties View file @ 46e0834
... ... @@ -29,6 +29,6 @@
29 29 redis.maxActive=600
30 30 redis.maxWait=1000
31 31 redis.testOnBorrow=true
32   -redis.HttpSession.redisNamespace=hospital.mac
  32 +redis.HttpSession.redisNamespace=hospital
33 33 spring.redis.cluster.max-redirects= 3
parent/hospital.web/src/main/resources/xml/app-shiro.xml View file @ 46e0834
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<beans xmlns="http://www.springframework.org/schema/beans"
  3 + xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
  4 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5 + xsi:schemaLocation="
  6 + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7 + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
  8 + http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  9 +
  10 + <!-- 开启Apache Shiro注解 否则使用SHIRO的注解后 @Autowired注解将会失效 -->
  11 + <aop:config proxy-target-class="true"></aop:config>
  12 + <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  13 + <property name="securityManager" ref="securityManager"/>
  14 + </bean>
  15 +
  16 + <!-- rememberMe-->
  17 + <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
  18 + <constructor-arg value="rememberMe"/>
  19 + <property name="httpOnly" value="true"/>
  20 + <property name="maxAge" value="2592000"/><!-- 30天 -->
  21 + </bean>
  22 +
  23 + <!-- rememberMe管理器 -->
  24 + <bean id="rememberMeManager"
  25 + class="org.apache.shiro.web.mgt.CookieRememberMeManager">
  26 + <!--<property name="cipherKey" value="\#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>-->
  27 + <property name="cookie" ref="rememberMeCookie"/>
  28 + </bean>
  29 +
  30 + <bean id="shiroRealm" class="com.lyms.hospital.shiro.ShiroRealm"/>
  31 + <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  32 + <property name="realm" ref="shiroRealm" />
  33 + <property name="rememberMeManager" ref="rememberMeManager"/>
  34 + </bean>
  35 +
  36 + <bean id="forceLogoutFilter" class="com.lyms.web.filter.ForceLogoutFilter"/>
  37 + <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  38 + <property name="securityManager" ref="securityManager" />
  39 + <property name="loginUrl" value="/login/tokens" />
  40 + <property name="successUrl" value="/index" />
  41 + <property name="filters">
  42 + <util:map>
  43 + <entry key="forceLogout" value-ref="forceLogoutFilter"/>
  44 + </util:map>
  45 + </property>
  46 + <property name="filterChainDefinitions">
  47 + <value>
  48 + /login/tokens = anon
  49 + /** = user,forceLogout
  50 + <!--
  51 + /logout = logout
  52 + /captcha/* = anon
  53 + /upload/* = anon
  54 + /static/** = anon
  55 + /dubboService/** = anon
  56 + /authenticated = authc
  57 + /test/** = anon
  58 + -->
  59 + </value>
  60 + </property>
  61 + </bean>
  62 + <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
  63 +</beans>
parent/hospital.web/src/main/webapp/WEB-INF/web.xml View file @ 46e0834
... ... @@ -58,6 +58,20 @@
58 58 <url-pattern>/*</url-pattern>
59 59 </filter-mapping>
60 60 <filter>
  61 + <filter-name>shiroFilter</filter-name>
  62 + <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  63 + <async-supported>true</async-supported>
  64 + <init-param>
  65 + <param-name>targetFilterLifecycle</param-name>
  66 + <param-value>true</param-value>
  67 + </init-param>
  68 + </filter>
  69 + <filter-mapping>
  70 + <filter-name>shiroFilter</filter-name>
  71 + <url-pattern>/*</url-pattern>
  72 + <dispatcher>REQUEST</dispatcher>
  73 + </filter-mapping>
  74 + <filter>
61 75 <filter-name>springSessionRepositoryFilter</filter-name>
62 76 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
63 77 </filter>