您的位置:首页 > 编程语言 > Java开发

shiro与spring整合的配置(第一种)

2017-04-26 15:11 302 查看
web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml,classpath:spring/quartz.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<filter>
<filter-name>sitemeshFilter</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemeshFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>CaptchaServlet</servlet-name>
<servlet-class>com.impay.boss.auth.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CaptchaServlet</servlet-name>
<url-pattern>/servlet/captchaCode</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>PublicServlet</servlet-name>
<servlet-class>com.impay.boss.servlet.PublicServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PublicServlet</servlet-name>
<url-pattern>/servlet/public</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>cacheSysConfig</servlet-name>
<servlet-class>com.impay.boss.servlet.CacheServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>*.swf</url-pattern>
<url-pattern>*.zip</url-pattern>
<url-pattern>*.xml</url-pattern>
<url-pattern>*.txt</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>uploadFile</servlet-name>
<servlet-class>com.impay.boss.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadFile</servlet-name>
<url-pattern>/servlet/upload</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/pagebar.tld</taglib-uri>
<taglib-location>/WEB-INF/pagebar.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/util.tld</taglib-uri>
<taglib-location>/WEB-INF/util.tld</taglib-location>
</taglib>
</jsp-config>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>

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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-lazy-init="true">

<description>Shiro Configuration</description>

<!-- 用来做登录用户验证 -->
<bean id="shiroDbRealm" class="com.impay.boss.auth.ShiroDbRealm" />

<!-- Shiro Filter -->
<bean id="myCaptchaFilter" class="com.impay.boss.auth.FormAuthenticationCaptchaFilter" />
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/index" />
<property name="filters">
<map>
<entry key="mcaptcha" value-ref="myCaptchaFilter" />
</map>
</property>

<property name="filterChainDefinitions">
<value>
/login = mcaptcha
/logout = logout
/images/** = anon
/scripts/** = anon
/thems/** = anon
/servlet/** = anon
/merreg/** = anon
/mobile/** = anon
/uploads/mobile_mers_files/** = anon
/uploadSign/** = anon
/areaInfo/findCity = anon
/cnaps/cnapslist = anon
/*.ico = anon
/IMer/add = anon
/IMer/findByMer = anon
/IMer/reapplyMer = anon
/** = user
</value>
</property>
</bean>

<!-- Shiro's main business-tier object for web-enabled applications -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroDbRealm" />
<property name="cacheManager" ref="shiroCacheManager" />
</bean>

<!-- 用户授权信息Cache -->
<bean id="shiroCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

<!-- 保证实现了Shiro内部lifecycle函数的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>

shiroDbRealm实现
package com.impay.boss.auth;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.impay.boss.domain.BossAuth;
import com.impay.boss.domain.BossUser;
import com.impay.boss.service.UserService;
import com.impay.boss.utils.IPUtils;

/**
* 登录系统后,对用户进行检验,包括严重和授权
*
* @author dj
*
*/
@Component
public class ShiroDbRealm extends AuthorizingRealm {

private static final Logger log = LoggerFactory
.getLogger(ShiroDbRealm.class);

@Autowired
private UserService userService;

// 设置密码加密方式为MD5
public ShiroDbRealm() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(
Md5Hash.ALGORITHM_NAME);
setCredentialsMatcher(matcher);

}

// 用户验证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken) authcToken;
// System.out.println(token.getUsername() + "=====");
// 增加判断验证码逻辑
String captcha = token.getCaptcha();
String exitCode = (String) SecurityUtils.getSubject().getSession()
.getAttribute(CaptchaServlet.KEY_CAPTCHA);
if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) {
throw new CaptchaException("验证码错误");
}

if (authcToken.getPrincipal() == null)
return null;
log.info("User login: {}", authcToken.getPrincipal());
BossUser user = null;
try {
user = userService
.getByUserName((String) authcToken.getPrincipal());
} catch (Exception e) {
log.error("query user exception", e);
}

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();

if (user == null) {
request.setAttribute(
FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
"IncorrectCredentialsException");
return null;
}
//暂停密码定时更改验证
/* if(!isUpdatePw(user.getUpdatePasswTime())){
request.setAttribute("LOGINFLAG", "NoUpdatePasswordException");
return null;
}*/
String roleStatus = "0";

if (user != null ) {
roleStatus = userService.getByRole(user.getId());
}
if (user != null && (Integer.parseInt(user.getStatus()) == 0 || Integer.parseInt(roleStatus) == 0)) {
request.setAttribute(
FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
"UnknownAccountException");
return null;
}

try {
if (userService.getAuthSize(user.getId())) {
request.setAttribute("UNAUTH","UnknownAuthAccountException");
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
String ip = IPUtils.getIpAddr(request);

List<Map<String,Object>> ipList = userService.getUserIpInfo(user);
boolean flag = false;
if(ipList.size()>0){
for (Map<String, Object> map : ipList) {
if (map.containsValue(ip)) {
flag = true;
}
}
if (flag) {
return new SimpleAuthenticationInfo(user, user.getPassword(),
getName());
} else {
return null;
}

}

return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
private boolean isUpdatePw(Date updateTime){
if(updateTime==null){
return false;
}
long nd = 1000*24*60*60;//一天的毫秒数
long diff = new Date().getTime() - updateTime.getTime();
if((diff/nd)>30){
return false;
}
return true;

}
// 用户授权
// TODO
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
BossUser bu = (BossUser) principals.fromRealm(getName()).iterator()
.next();
if (bu == null) {
return null;
}

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
List<BossAuth> bas;
try {
bas = userService.getAuthList(bu.getId());

userService.failTimesInit(bu.getUserName());

for (BossAuth b : bas) {
info.addStringPermission(StringUtils.trim(b.getAuthCode()));
}
} catch (SQLException e) {
e.printStackTrace();
}
return info;
}

@Override
public boolean supports(AuthenticationToken token) {
return super.supports(token);
}

}


myCaptchaFilter实现
package com.impay.boss.auth;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.impay.boss.domain.BossUser;
import com.impay.boss.service.AgentService;
import com.impay.boss.service.UserService;

public class FormAuthenticationCaptchaFilter extends FormAuthenticationFilter {

@Resource
private AgentService agentService;
@Resource
private UserService userService;

private ReentrantLock lock=new ReentrantLock();

public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

private String captchaParam = DEFAULT_CAPTCHA_PARAM;

public String getCaptchaParam() {

return captchaParam;

}

protected String getCaptcha(ServletRequest request) {

return WebUtils.getCleanParam(request, getCaptchaParam());

}

protected AuthenticationToken createToken(ServletRequest request,
ServletResponse response) {

String username = getUsername(request);

String password = getPassword(request) == null ? "" : getPassword(request);

String captcha = getCaptcha(request);

boolean rememberMe = isRememberMe(request);

String host = getHost(request);

return new UsernamePasswordCaptchaToken(username,

password.toCharArray(), rememberMe, host, captcha);

}

// 登录成功操作,这里设置了代理商常用信息
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
Subject subject, ServletRequest request, ServletResponse response)
throws Exception {
BossUser bossUser = (BossUser) SecurityUtils.getSubject()
.getPrincipal();
HttpSession session = WebUtils.toHttp(request).getSession(true);

session.setAttribute("user", bossUser);
session.setAttribute("power", userService.checkPower(bossUser.getId()));
Map<String, String> param = new HashMap<String, String>();
WebUtils.issueRedirect(request, response, getSuccessUrl(), param, true);
// save log
String ip = request.getRemoteAddr();
userService.saveLog(ip, bossUser);
/* try{
lock.lock();
ServletContext application = ((HttpServletRequest)request).getSession().getServletContext();
if(application.getAttribute(bossUser.getUserName())==null){
application.setAttribute(bossUser.getUserName(), session);
}
}catch (Exception e) {
throw new Exception(e.getMessage());
}finally{
lock.unlock();
}*/
return false;
}

}
UsernamePasswordCaptchaToken实现
package com.impay.boss.auth;

import org.apache.shiro.authc.UsernamePasswordToken;

public class UsernamePasswordCaptchaToken extends UsernamePasswordToken {

private static final long serialVersionUID = 1L;

private String captcha;

public String getCaptcha() {

return captcha;

}

public void setCaptcha(String captcha) {

this.captcha = captcha;

}

public UsernamePasswordCaptchaToken() {

super();

}

public UsernamePasswordCaptchaToken(String username, char[] password,

boolean rememberMe, String host, String captcha) {

super(username, password, rememberMe, host);

this.captcha = captcha;

}

}


数据库部分SQL部分:
boss_user;



boss_role_auth



 boss_role;



boss_auth

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: