Skip to content

Commit

Permalink
add shiro config
Browse files Browse the repository at this point in the history
  • Loading branch information
leelance committed Jan 3, 2017
1 parent 2b08e22 commit 7faf0b4
Show file tree
Hide file tree
Showing 4 changed files with 342 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.lance.activiti.common.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.lance.activiti.model.UserInfo;
import com.lance.activiti.service.user.UserService;
import com.lance.activiti.utils.ShiroSessionUtils;

public class FormAuthenticationFilterExt extends FormAuthenticationFilter {
@Autowired
private UserService userService;
/**adminValidCode*/
public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
/**LoginMessage*/
public static final String DEFAULT_MESSAGE_PARAM = "message";

private String captchaParam = DEFAULT_CAPTCHA_PARAM;
private String messageParam = DEFAULT_MESSAGE_PARAM;


@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String username = getUsername(request);
String password = getPassword(request);
if (password==null){
password = "";
}
boolean rememberMe = isRememberMe(request);
String host = "";
String captcha = getCaptcha(request);
return new UsernamePasswordCaptchaToken(username, password.toCharArray(), rememberMe, host, captcha);
}

@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
String className = e.getClass().getName(), message = "";
if (IncorrectCredentialsException.class.getName().equals(className)
|| UnknownAccountException.class.getName().equals(className)){
message = "用户或密码错误, 请重试.";
}else {
message = e.getMessage();
}
request.setAttribute(getFailureKeyAttribute(), className);
request.setAttribute(getMessageParam(), message);
return true;
}

@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
UserInfo user = userService.findByAccount(getUsername(request));
ShiroSessionUtils.setAdminLogin(user);
return super.onLoginSuccess(token, subject, request, response);
}

protected String getCaptcha(ServletRequest request) {
return WebUtils.getCleanParam(request, getCaptchaParam());
}

public String getCaptchaParam() {
return captchaParam;
}

public String getMessageParam() {
return messageParam;
}

public void setCaptchaParam(String captchaParam) {
this.captchaParam = captchaParam;
}

public void setMessageParam(String messageParam) {
this.messageParam = messageParam;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package com.lance.activiti.common.shiro;

import java.util.Map;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.filter.DelegatingFilterProxy;

import com.google.common.collect.Maps;

@Configuration
public class ShiroConfig {

/**
* FilterRegistrationBean
* @return
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
return filterRegistration;
}

/**
* @see org.apache.shiro.spring.web.ShiroFilterFactoryBean
* @return
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter(){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(securityManager());
bean.setLoginUrl("/login");
bean.setSuccessUrl("/admin/welcome");

Map<String, Filter>filters = Maps.newHashMap();
filters.put("authc", formAuthenticationFilter());
bean.setFilters(filters);

Map<String, String> chains = Maps.newHashMap();
chains.put("/login", "authc");
chains.put("/logout", "logout");
chains.put("/**/*.js", "anon");
chains.put("/**/*.css", "anon");
chains.put("/**/*.jpg", "anon");
chains.put("/**/*.jpeg", "anon");
chains.put("/**/*.png", "anon");
chains.put("/kaptcha/**", "anon");
chains.put("/error/**", "anon");
chains.put("/admin/**", "user");
bean.setFilterChainDefinitionMap(chains);
return bean;
}

@Bean
public FormAuthenticationFilterExt formAuthenticationFilter(){
return new FormAuthenticationFilterExt();
}


/**
* @see org.apache.shiro.mgt.SecurityManager
* @return
*/
@Bean(name="securityManager")
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(userRealm());
manager.setCacheManager(cacheManager());
manager.setSessionManager(defaultWebSessionManager());
return manager;
}

@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean factoryBean = new MethodInvokingFactoryBean();
factoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
factoryBean.setArguments(new Object[]{securityManager()});
return factoryBean;
}

/**
* @see DefaultWebSessionManager
* @return
*/
@Bean
public DefaultWebSessionManager defaultWebSessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setCacheManager(cacheManager());
sessionManager.setGlobalSessionTimeout(1800000);
sessionManager.setDeleteInvalidSessions(true);
sessionManager.setSessionValidationSchedulerEnabled(true);
//sessionManager.setSessionDAO(new EnterpriseCacheSessionDAO());//可以重写sessionDao
return sessionManager;
}

/**
* @see UserRealm--->AuthorizingRealm
* @return
*/
@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public UserRealm userRealm() {
UserRealm userRealm = new UserRealm();
userRealm.setCacheManager(cacheManager());
return userRealm;
}

@Bean
public EhCacheManager cacheManager() {
EhCacheManager cacheManager = new EhCacheManager();
cacheManager.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return cacheManager;
}

@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}

@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator auto = new DefaultAdvisorAutoProxyCreator();
auto.setProxyTargetClass(true);
return auto;
}

@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager());
return advisor;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.lance.activiti.common.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lance.activiti.common.SystemConstants;
import com.lance.activiti.model.UserInfo;
import com.lance.activiti.service.user.UserService;
import com.lance.activiti.utils.ShiroSessionUtils;

@Component
public class UserRealm extends AuthorizingRealm {
private Logger logger = LogManager.getLogger(getClass());
@Autowired
private UserService userService;

public UserRealm() {
setName("userRealm");
setCredentialsMatcher(new HashedCredentialsMatcher("md5"));
setAuthenticationTokenClass(UsernamePasswordCaptchaToken.class);
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//String account = (String)principals.getPrimaryPrincipal();
//UserInfo user = userService.findByAccount(account);
//授予角色, 目前不处理资源Permission TODO
info.addRole("admin");
return info;
}

/**
* 验证码登录信息
* @author lance
* @since 2016年11月5日下午11:48:56
* @param authToken
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken)authToken;
String validCode = ShiroSessionUtils.getValue(SystemConstants.ADMIN_VALID_KEY)+"";

if (logger.isDebugEnabled()){
logger.debug("Login===> username: {}, Captcha: {}", token.getUsername(), token.getCaptcha());
}

//验证码是否正确
if(!StringUtils.equalsIgnoreCase(validCode, token.getCaptcha())) {
throw new AuthenticationException("验证码错误, 请重试");
}

//验证码用户是否
UserInfo user = userService.findByAccount(token.getUsername());
if(user != null) {
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword().toCharArray(), getName());
return authenticationInfo;
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.lance.activiti.common.shiro;

import org.apache.shiro.authc.UsernamePasswordToken;

/**
* 后台用户登录
* @author lance
* @since 2016年11月5日下午2:24:32
*/
public class UsernamePasswordCaptchaToken extends UsernamePasswordToken {
private static final long serialVersionUID = -2516621696792507680L;

/**验证码*/
private String captcha;

public UsernamePasswordCaptchaToken() {
super();
}

public UsernamePasswordCaptchaToken(String username, char[] password,
boolean rememberMe, String host, String captcha) {
super(username, password, rememberMe, host);
this.captcha = captcha;
}

public String getCaptcha() {
return captcha;
}

public void setCaptcha(String captcha) {
this.captcha = captcha;
}
}

0 comments on commit 7faf0b4

Please sign in to comment.