SpringMVC整合shiro許可權(附原始碼)
阿新 • • 發佈:2018-12-30
springMVC框架這裡就不多說了,下面是在springMVC框架上面直接整合shiro程式碼步驟
下面是我專案結構:
1、web.xml新增Shiro Filter
<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>
2、新增applicationContext-shiro.xml檔案
applicationContext-shiro.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"
default-lazy-init="true">
<description>Shiro Configuration</description>
<!-- shiroFilter工廠 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 構建securityManager環境 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登入時的連結(可根據專案的URL進行替換),非必須的屬性,預設會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
<property name="loginUrl" value="/sys/auth/logon"/>
<!-- 登入成功後要跳轉的連線 -->
<property name="successUrl" value="/sys/main"/>
<!-- 沒有許可權返回的地址 (拒絕訪問路徑)-->
<property name="unauthorizedUrl" value="/sys/auth/refused" />
<property name="filterChainDefinitions">
<value>
/static/**=anon
/sys/auth/login=anon
/sys/auth/logout=anon
/**=authc
</value>
</property>
</bean>
<!-- securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--呼叫自定義realm -->
<property name="realm" ref="realm" />
</bean>
<bean id="realm" class="com.qianxunclub.admin.sys.shiro.Realm"></bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- AOP式方法級許可權檢查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
realm這裡主要是設定自定義的單Realm應用,若有多個Realm,可使用’realms’屬性代替,改配置也是主要的校驗邏輯
3、新增Realm類
package com.qianxunclub.admin.sys.shiro;
import com.qianxunclub.admin.sys.constant.SysConstant;
import com.qianxunclub.admin.sys.model.domain.SysResource;
import com.qianxunclub.admin.sys.model.domain.SysRole;
import com.qianxunclub.admin.sys.model.domain.SysUser;
import com.qianxunclub.admin.sys.model.request.SysResourceParam;
import com.qianxunclub.admin.sys.model.request.SysRoleParam;
import com.qianxunclub.admin.sys.service.SysResourceService;
import com.qianxunclub.admin.sys.service.SysRoleService;
import com.qianxunclub.admin.sys.service.SysUserService;
import com.qianxunclub.util.Encodes;
import com.qianxunclub.util.StringUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static com.qianxunclub.util.Encodes.encodeToMD5;
public class Realm extends AuthorizingRealm {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private SysUserService sysUserService;
@Autowired
private SysRoleService sysRoleService;
@Autowired
private SysResourceService sysResourceService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String)super.getAvailablePrincipal(principalCollection);
if(StringUtil.isNotEmpty(username)){
//從資料庫中獲取當前登入使用者的詳細資訊
SysUser sysUser = sysUserService.getByUsername(username).getDataInfo();
if(sysUser == null){
throw new AuthorizationException();
}
//為當前使用者設定角色和許可權
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
List<String> roleList = new ArrayList<String>();
SysRoleParam sysRoleParam = new SysRoleParam();
sysRoleParam.setUserId(sysUser.getId());
sysRoleParam.setOrgId(sysUser.getOrgId());
List<SysRole> sysRoles = sysRoleService.roleListByUser(sysRoleParam);
for(SysRole sysRole : sysRoles){
roleList.add(sysRole.getId());
}
List<String> permissionList = new ArrayList<String>();
SysResourceParam param = new SysResourceParam();
param.setRoleList(roleList);
List<SysResource> sysResourceList = sysResourceService.resourceListByRole(param);
for(SysResource sysResource : sysResourceList){
permissionList.add(sysResource.getId());
}
simpleAuthorInfo.addRoles(roleList);
simpleAuthorInfo.addStringPermissions(permissionList);
return simpleAuthorInfo;
} else {
return null;
}
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
SysUser sysUser = sysUserService.getByUsername(token.getUsername()).getDataInfo();
if (null != sysUser) {
String password = Encodes.encodeToMD5(new String(token.getPassword()) + sysUser.getSalt());
token.setPassword(password.toCharArray());
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(sysUser.getUsername(), sysUser.getPassword(), sysUser.getName());
this.setSession(SysConstant.USER_SESSION, sysUser);
return authcInfo;
} else {
return null;
}
//沒有返回登入使用者名稱對應的SimpleAuthenticationInfo物件時,就會在LoginController中丟擲UnknownAccountException異常
}
/**
* 將一些資料放到ShiroSession中,以便於其它地方使用
* 比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到
*/
private void setSession(String key, Object value){
Subject currentUser = SecurityUtils.getSubject();
if(null != currentUser){
Session session = currentUser.getSession();
if(null != session){
session.setAttribute(key, value);
}
}
}
}
4、下面就是授權的controller和service了
我這裡登陸的邏輯都寫在service裡面,controller只做了一個接受引數的步驟
AuthController.java
package com.qianxunclub.admin.sys.controller;
import com.qianxunclub.admin.sys.model.request.SysUserParam;
import com.qianxunclub.admin.sys.service.AuthService;
import com.qianxunclub.context.controller.BaseController;
import com.qianxunclub.util.BaseResponse;
import com.qianxunclub.util.HttpResponseUtil;
import com.qianxunclub.util.JsonUtil;
import com.qianxunclub.util.ReturnCode;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping(value = "/sys/auth")
public class AuthController extends BaseController {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private AuthService authService;
@RequestMapping(value = "/logon", method = {RequestMethod.POST,RequestMethod.GET})
public String logon(HttpServletResponse resp) {
return "login";
}
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, HttpServletResponse resp, SysUserParam param) {
BaseResponse baseResponse;
baseResponse = param.validate();
if(!baseResponse.isSuccess()){
String responseStr = JsonUtil.objectToJson(baseResponse);
HttpResponseUtil.setResponseJsonBody(resp, responseStr);
return;
}
baseResponse = authService.login(request,param);
String responseStr = JsonUtil.objectToJson(baseResponse);
HttpResponseUtil.setResponseJsonBody(resp, responseStr);
}
@ResponseBody
@RequestMapping(value = "/relogin", method = {RequestMethod.POST,RequestMethod.GET})
public void relogin(HttpServletResponse resp) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setReturn(ReturnCode.CODE_1008);
String responseStr = JsonUtil.objectToJson(baseResponse);
HttpResponseUtil.setResponseJsonBody(resp, responseStr);
}
@ResponseBody
@RequestMapping(value = "/refused", method = {RequestMethod.POST,RequestMethod.GET})
public void refused(HttpServletResponse resp) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setReturn(ReturnCode.CODE_1001);
String responseStr = JsonUtil.objectToJson(baseResponse);
HttpResponseUtil.setResponseJsonBody(resp, responseStr);
}
@ResponseBody
@RequestMapping(value = "/logout", method = {RequestMethod.POST,RequestMethod.GET})
public void logout(HttpServletResponse resp) {
BaseResponse baseResponse = new BaseResponse();
authService.logout();
baseResponse.setReturn(ReturnCode.CODE_1000);
String responseStr = JsonUtil.objectToJson(baseResponse);
HttpResponseUtil.setResponseJsonBody(resp, responseStr);
}
}
AuthService.java
package com.qianxunclub.admin.sys.service;
import com.qianxunclub.admin.sys.constant.MassageConstant;
import com.qianxunclub.admin.sys.constant.SysConstant;
import com.qianxunclub.admin.sys.model.domain.SysUser;
import com.qianxunclub.admin.sys.model.request.SysUserParam;
import com.qianxunclub.context.service.MessageService;
import com.qianxunclub.util.BaseResponse;
import com.qianxunclub.util.ReturnCode;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* Created by zhangbin on 2017/3/10.
*/
@Component
public class AuthService {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private MessageService messageService;
@Autowired
private SysUserRoleService sysUserRoleService;
public BaseResponse login(HttpServletRequest request,SysUserParam param){
BaseResponse baseResponse;
baseResponse = this.validateUser(param);
if(!baseResponse.isSuccess()){
return baseResponse;
}
SysUser sysUser = (SysUser)request.getSession().getAttribute(SysConstant.USER_SESSION);
return baseResponse;
}
public void logout() {
SecurityUtils.getSubject().logout();
}
private BaseResponse validateUser(SysUserParam param){
BaseResponse baseResponse = new BaseResponse();
String message = null;
Integer code = ReturnCode.CODE_1000.code();
String username = param.getUsername();
String password = param.getPassword();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(param.isRememberMe());
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (UnknownAccountException uae) {
message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
logger.error(message,uae);
} catch (IncorrectCredentialsException ice) {
message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
logger.error(message,ice);
} catch (LockedAccountException lae) {
message = messageService.message(MassageConstant.LOGIN_USER_LOCK);
logger.error(message,lae);
} catch (ExcessiveAttemptsException eae) {
message = messageService.message(MassageConstant.LOGIN_USER_MORE);
logger.error(message,eae);
} catch (AuthenticationException ae) {
//通過處理Shiro的執行時AuthenticationException就可以控制使用者登入失敗或密碼錯誤時的情景
message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
logger.error(message,ae);
}
//驗證是否登入成功
if (!subject.isAuthenticated()) {
code = ReturnCode.CODE_1006.code();
token.clear();
}
baseResponse.setReturnCode(code);
baseResponse.setMessage(message);
return baseResponse;
}
}
下面是定義的常量提示語
/**
*使用者名稱或密碼錯誤
*/
public static final String LOGIN_USER_REEOE = "LOGIN_USER_REEOE";
/**
*使用者被鎖定
*/
public static final String LOGIN_USER_LOCK = "LOGIN_USER_LOCK";
/**
*密碼錯誤次數已達上限
*/
public static final String LOGIN_USER_MORE = "LOGIN_USER_MORE";
到這裡就已經完成了shiro的添加了,啟動程式,體驗一把吧!
附件
程式碼是使用maven構建的,maven就不多說了
改程式依賴了我的另一個jar包,也需要下載編譯的
下載完成後,在asone-core根目錄執行
mvn clean install -Dmaven.test.skip=true
完成後,開啟asone專案,啟動就可以成功啟動了