zheng-upms接入shiro认证和授权

This commit is contained in:
shuzheng 2017-01-21 00:54:54 +08:00
parent 958fabf638
commit 4e5df0ece2
8 changed files with 190 additions and 12 deletions

View File

@ -76,7 +76,7 @@
<!-- shiro --> <!-- shiro -->
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId> <artifactId>shiro-spring</artifactId>
<version>1.3.2</version> <version>1.3.2</version>
</dependency> </dependency>
<!-- mybatis --> <!-- mybatis -->

View File

@ -54,8 +54,8 @@
<!-- 配置静态资源不被DispatcherServlet处理增加缓存时间 --> <!-- 配置静态资源不被DispatcherServlet处理增加缓存时间 -->
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="10" /> <mvc:resources mapping="/resources/**" location="/resources/" cache-period="10" />
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<!-- 上传文件配置 20*1024*1024即20M resolveLazily属性启用是为了推迟文件解析以便捕获文件大小异常 --> <!-- 上传文件配置 20*1024*1024即20M resolveLazily属性启用是为了推迟文件解析以便捕获文件大小异常 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

View File

@ -10,6 +10,12 @@ import com.zheng.upms.dao.model.UpmsUserExample;
import com.zheng.upms.rpc.api.UpmsSystemService; import com.zheng.upms.rpc.api.UpmsSystemService;
import com.zheng.upms.rpc.api.UpmsUserService; import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -28,6 +34,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;
/** /**
* 单点登录管理 * 单点登录管理
* Created by shuzheng on 2016/12/10. * Created by shuzheng on 2016/12/10.
@ -140,20 +148,38 @@ public class SSOController {
result.put("data", SystemConstant.NO_PASSWORD); result.put("data", SystemConstant.NO_PASSWORD);
return result; return result;
} }
// 校验帐号密码 // // 校验帐号密码
UpmsUserExample upmsUserExample = new UpmsUserExample(); // UpmsUserExample upmsUserExample = new UpmsUserExample();
upmsUserExample.createCriteria() // upmsUserExample.createCriteria()
.andUsernameEqualTo(username); // .andUsernameEqualTo(username);
UpmsUser upmsUser = upmsUserService.selectFirstByExample(upmsUserExample); // UpmsUser upmsUser = upmsUserService.selectFirstByExample(upmsUserExample);
if (null == upmsUser) { // if (null == upmsUser) {
// result.put("result", false);
// result.put("data", SystemConstant.ERROR_USERNAME);
// return result;
// }
// if (!upmsUser.getPassword().equals(MD5Util.MD5(password + upmsUser.getSalt()))) {
// result.put("result", false);
// result.put("data", SystemConstant.ERROR_PASSWORD);
// return result;
// }
// 使用shiro认证
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
try {
subject.login(usernamePasswordToken);
} catch (UnknownAccountException e) {
result.put("result", false); result.put("result", false);
result.put("data", SystemConstant.ERROR_USERNAME); result.put("data", SystemConstant.ERROR_USERNAME);
return result; return result;
} } catch (IncorrectCredentialsException e) {
if (!upmsUser.getPassword().equals(MD5Util.MD5(password + upmsUser.getSalt()))) {
result.put("result", false); result.put("result", false);
result.put("data", SystemConstant.ERROR_PASSWORD); result.put("data", SystemConstant.ERROR_PASSWORD);
return result; return result;
} catch (LockedAccountException e) {
result.put("result", false);
result.put("data", SystemConstant.INVALID_ACCOUNT);
return result;
} }
// 分配单点登录sessionId不使用session获取会话id改为cookie防止session丢失 // 分配单点登录sessionId不使用session获取会话id改为cookie防止session丢失
String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SSO_SERVER_SESSION_ID); String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SSO_SERVER_SESSION_ID);

View File

@ -2,6 +2,9 @@ package com.zheng.upms.admin.controller.manage;
import com.zheng.upms.dao.model.UpmsSystemExample; import com.zheng.upms.dao.model.UpmsSystemExample;
import com.zheng.upms.rpc.api.UpmsSystemService; import com.zheng.upms.rpc.api.UpmsSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -14,6 +17,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
* Created by shuzheng on 2016/12/18. * Created by shuzheng on 2016/12/18.
*/ */
@Controller @Controller
@Api(value = "系统管理", description = "注册系统管理")
@RequestMapping("/manage/system") @RequestMapping("/manage/system")
public class SystemController { public class SystemController {
@ -22,12 +26,17 @@ public class SystemController {
@Autowired @Autowired
private UpmsSystemService upmsSystemService; private UpmsSystemService upmsSystemService;
@ApiOperation(value = "系统首页")
@RequiresPermissions("upms.system.read")
//@RequiresUser
@RequestMapping("/index") @RequestMapping("/index")
public String index() { public String index() {
return "/manage/system/index"; return "/manage/system/index";
} }
@ApiOperation(value = "系统列表")
@RequiresPermissions("upms.system.read")
//@RequiresUser
@RequestMapping("/list") @RequestMapping("/list")
@ResponseBody @ResponseBody
public Object list() { public Object list() {

View File

@ -0,0 +1,80 @@
package com.zheng.upms.admin.realm;
import com.zheng.common.util.MD5Util;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.dao.model.UpmsUserExample;
import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;
/**
* Created by shuzheng on 2017/1/20.
*/
public class UpmsRealm extends AuthorizingRealm {
private static Logger _log = LoggerFactory.getLogger(UpmsRealm.class);
@Autowired
private UpmsUserService upmsUserService;
/**
* 授权验证权限时调用
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 当前用户
UpmsUser upmsUser = (UpmsUser) principalCollection.getPrimaryPrincipal();
_log.info("授权upmsUser={}", upmsUser);
// 全部权限 TODO
Set<String> permissions = new HashSet<>();
permissions.add("*:*:*");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setStringPermissions(permissions);
return simpleAuthorizationInfo;
}
/**
* 认证登录时调用
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username = (String) authenticationToken.getPrincipal();
String password = new String((char[]) authenticationToken.getCredentials());
_log.info("认证username={}, password={}", username, password);
// 查询用户信息
UpmsUserExample upmsUserExample = new UpmsUserExample();
upmsUserExample.createCriteria()
.andUsernameEqualTo(username);
UpmsUser upmsUser = upmsUserService.selectFirstByExample(upmsUserExample);
if (null == upmsUser) {
throw new UnknownAccountException("帐号不存在!");
}
if (!upmsUser.getPassword().equals(MD5Util.MD5(password + upmsUser.getSalt()))) {
throw new IncorrectCredentialsException("密码错误!");
}
if (upmsUser.getStatus() == -1) {
throw new LockedAccountException("账号已被锁定!");
}
return new SimpleAuthenticationInfo(upmsUser, password, getName());
}
}

View File

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<description>zheng-upms</description>
<!--设置自定义realm继承自AuthorizingRealm -->
<bean id="upmsRealm" class="com.zheng.upms.admin.realm.UpmsRealm"></bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="upmsRealm"/>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/sso/login"/>
<property name="successUrl" value="/manage"/>
<property name="unauthorizedUrl" value="/403"/>
<property name="filterChainDefinitions">
<value>
swagger-ui.html = anon
/webjars/** = anon
/resources/** = anon
/sso/login = anon
/manage/**=authc
</value>
</property>
</bean>
<!-- 设置SecurityUtils -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
<property name="arguments" ref="securityManager"/>
</bean>
<!-- @RequiresPermissions注解支持 -->
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>

View File

@ -90,6 +90,9 @@
if (10005 == json.data) { if (10005 == json.data) {
alert("密码错误!"); alert("密码错误!");
} }
if (10006 == json.data) {
alert("帐号被封!");
}
} }
}, },
error: function(error){ error: function(error){

View File

@ -89,6 +89,20 @@
<url-pattern>/manage/*</url-pattern> <url-pattern>/manage/*</url-pattern>
</filter-mapping> </filter-mapping>
<!-- shiro -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Druid连接池监控页面 --> <!-- Druid连接池监控页面 -->
<servlet> <servlet>
<servlet-name>DruidStatView</servlet-name> <servlet-name>DruidStatView</servlet-name>