p4jsecurity(内测版) -- Spring Security 3 界面化管理权限功能 扩展

一套高颜值的权限管理系统UI 本项目是一套权限管理系统的用户界面(UI)实现,采用 JavaFX 技术开发。该系统的用户界面参考了若依前端框架基于 RuoYi-Vue 的设计风格,旨在提供一套免费使用的权限管理系统。采用 mvvmFX 框架,该框架基于 MVVM (Model-View-ViewModel) 架构模式,用于实现数据绑定和视图模型的管理。使用 atlantafx 主题库,该主题库提供了一套现代化、响应式的用户界面风格,帮助美化系统的外观和用户体验。 阅读详情

(声明:本设计目前还没有应用于大型系统权限管理,不排除会有一些问题,仅作技术储备,便于后期查阅;本文中中的Demo并没有进行完整的重构,仅作技术参考)

场景:

1、界面化的管理权限、分配用户权限。(非配置文件、注解形式;可理解为界面化的添加具体权限信息,并分配指定用户权限)

2、依赖于Spring Security。对后期权限系统的扩展必然会有好处,但是查找文档没有发现Spring Security提供便利的方式界面化管理权限(或许Spring Security本身支持,只是我看的文档不够全面,如果已支持还请读者发本人相关资料,不胜感激 partner4java@163.com)。


下面的文章将主要围绕本人如何实现界面化管理解决的一些问题,并不涉及Spring Security的具体细节使用,建议对Spring Security有一定了解再阅读本篇文章,Spring Security可参照《 Spring Security HelloWorld 》 (http://blog.csdn.net/partner4java/article/details/7928000)。

以下内容主要分为三部分:

1、功能展示;

2、基本架构设计;

3、问题解决具体方式。

一:功能展示

Demo下载地址:http://download.csdn.net/detail/partner4java/5220557

SQL脚本:http://download.csdn.net/detail/partner4java/5220915

Demo登录地址:http://localhost:8080/security_test/login.jsp

账号:(admin 1234)

首先展示一下我们管理权限的界面:


用户管理界面:


点击用户对应的权限跳转至权限分配界面:


权限分配为复选框,若已存在的权限会已选中。

二:基本架构设计

1、为AuthenticationManager设置自定义的UserDetailsService加载自定义表中的用户信息(验证用户信息和获取用户权限)。

2、修改默认AccessDecisionManager,在决策之前加入界面维护权限数据。

3、定义AuthorityCacheBean,用于辅助自定义AccessDecisionManager获取指定地址应该匹配的权限,并加入了缓存策略。

4、权限声明entity Authority,为其添加boolean matchUrl(String url)方法,用于返回是否遵循地址匹配;添加boolean matchMethod(HttpMethod httpMethod)方法,用于判断是否匹配方法,采用“大于等于”范围方式。

5、改变自带决策AccessDecisionManager,改为“只需要当前访问所有匹配权限中有一条权限没有人投反对票且有人赞同,则用户可以通过”。

三:问题解决具体方式

改变为界面化管理权限、用户,无非就几点:

1.通过登录信息匹配到维护的用户;

2.根据用户匹配界面化维护的权限;

3.根据地址匹配到对应的界面化维护的权限;

4.改变投票策略为你所需要的方式。


1、通过登录信息匹配到维护的用户

这一点Spring Security已经提供,无需我们再做过多修改,只需要在配置文件中指定:

		<beans:property name="usersByUsernameQuery">
			<beans:value>
				select username,password,visible as enabled from Employee where username = ? 
			</beans:value>
		</beans:property>


2、 根据用户匹配界面化维护的权限

同第一点,可以配置形式,我们这里借助了已有的User Service,便于后期统一加入缓存。

那么就需要重写原有的JdbcDaoImpl:

public class DefalutJdbcDaoImpl extends JdbcDaoImpl {
	private Log logger = LogFactory.getLog(DefalutJdbcDaoImpl.class);

	private EmployeeService employeeService;

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	@Override
	protected List<GrantedAuthority> loadUserAuthorities(String username) {
		// List<GrantedAuthority> grantedAuthoritys =
		// super.loadUserAuthorities(username);
		List<GrantedAuthority> grantedAuthoritys = new LinkedList<GrantedAuthority>();

		Employee employee = employeeService.getEmployee(username);
		if (employee != null) {
			Set<Authority> authorities = employee.getAuthorities();
			if (authorities != null) {
				for (Authority authority : authorities) {
					if (authority.getAuthority() != null && !"".equals(authority.getAuthority().trim())) {
						String roleName = getRolePrefix() + authority.getAuthority();
						grantedAuthoritys.add(new SimpleGrantedAuthority(roleName));
					}
				}
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("loadUserAuthorities() username: " + username + " grantedAuthoritys:" + grantedAuthoritys);
		}

		return grantedAuthoritys;
	}
}
若你还需要开通配置文件或其他形式形式添加权限,放开注释代码并合并数据库获取的权限即可。

配置文件:

	<!-- 通过默认的方式回去用户信息 -->
	<beans:bean id="userDetailsService"
		class="com.partner4java.security.core.userdetails.service.DefalutJdbcDaoImpl">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="usersByUsernameQuery">
			<beans:value>
				select username,password,visible as enabled from Employee where username = ? 
			</beans:value>
		</beans:property>
		<!-- <beans:property name="authoritiesByUsernameQuery">
			<beans:value>
				select u.username as username,a.authority as authority from employee u,Authority a,employee_authority au where u.username = ?  and u.EMPLOYEE_ID = au.EMPLOYEE_ID and a.AUTHORITY_ID = au.AUTHORITY_ID  and a.visible = 1  
			</beans:value>
		</beans:property> -->
		<beans:property name="employeeService" ref="employeeServiceBean"/>
	</beans:bean>

可以看到我们注释掉了配置的authoritiesByUsernameQuery,这种形式和匹配用户一样可以自己选择使用的方式。


3、根据地址匹配到对应的界面化维护的权限

这一点你可以从获取权限根部入手,我们这里修改的AccessDecisionManager。

但是有一点,我们如何知道当前访问的url和httpmethod呢(根部获取位置传入了request,我们这里并没有request参数传入)?

我们利用Filter,借助ThreadLocal,这里要注意一点当前线程可能会有多次请求,我们需要织入最新方式地址,也就是if (url.get() == null || (url.get() != null && !url.get().equals(rul)) || httpMethod.get() == null
|| (httpMethod.get() != null && !httpMethod.get().equals(request.getMethod())))

这个问题纠结了我好久,后来打印log才发现存在多次请求。

public class InitFilter implements Filter {
	private static Log logger = LogFactory.getLog(InitFilter.class);
	private static ThreadLocal<String> httpMethod = new ThreadLocal<String>();
	private static ThreadLocal<String> url = new ThreadLocal<String>();

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String rul = UrlUtils.buildRequestUrl(request);

		// 有些情况是单个线程存在多次访问
		if (url.get() == null || (url.get() != null && !url.get().equals(rul)) || httpMethod.get() == null
				|| (httpMethod.get() != null && !httpMethod.get().equals(request.getMethod()))) {
			url.set(rul);
			httpMethod.set(request.getMethod());

			if (logger.isDebugEnabled()) {
				logger.debug("doFilter() currentThread id: " + Thread.currentThread().getId());
				logger.debug("doFilter() fullRequestUrl:" + UrlUtils.buildFullRequestUrl(request) + " httpMethod:"
						+ request.getMethod());
			}
		}

		doSetCharsetencoding(req);
		chain.doFilter(req, rep);
	}

	/**
	 * 设置请求编码格式,一定要设置为filter链第一个
	 * 
	 * @param req
	 * @throws UnsupportedEncodingException
	 */
	private void doSetCharsetencoding(ServletRequest req) throws UnsupportedEncodingException {
		String charsetencoding = ((HttpServletRequest) req).getSession().getServletContext()
				.getInitParameter("request.charsetencoding");
		if (charsetencoding != null && !"".equals(charsetencoding.trim())) {
			req.setCharacterEncoding(charsetencoding);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	/**
	 * 返回当前请求类型
	 * 
	 * @return POST,GET等
	 */
	public static String getLocalMethod() {
		if (logger.isDebugEnabled()) {
			logger.debug("getLocalMethod() " + httpMethod.get() + "  currentThread id: "
					+ Thread.currentThread().getId());
		}
		return httpMethod.get();
	}

	/**
	 * 返回当前请求地址标识
	 * 
	 * @return
	 */
	public static String getLocalURL() {
		if (logger.isDebugEnabled()) {
			logger.debug("getLocalURL()  " + url.get() + " currentThread id: " + Thread.currentThread().getId());
		}
		return url.get();
	}
}
我们可以拿到url和httpmethod后,借助AuthorityCacheBean的getLocalMatchConfigAttributes()方法。AuthorityCacheBean很有意思,我们加入了定时器ThreadPoolUtil.scheduler.scheduleWithFixedDelay,间隔执行时间为我们重新载入权限的频率,当然在保证第一次加载成功的前提下你可以设置的长一些,我们这里只是为了测试更快的看到修改数据后的效果。
@Service
@Scope(value = "singleton")
public class AuthorityCacheBean implements AuthorityCache {
	/** 返回静态实例引用,并不保证本对象不为null,也不保证线程安全性 */
	public static AuthorityCacheBean singleton = null;

	/** 存放当前所有的权限,key为权限名称,value为权限对象 */
	private static Map<String, Authority> authorities = new HashMap<String, Authority>();

	/** 自定义配置的权限设置 -- 所有权限 */
	private static List<ConfigAttribute> configAttributes;

	/** URL地址和对应权限的对应 */
	private static ConcurrentMap<String, List<ConfigAttribute>> configUrlMap = new ConcurrentHashMap<String, List<ConfigAttribute>>();

	private static Log logger = LogFactory.getLog(AuthorityCacheBean.class);
	private AuthorityService authorityService;

	@Autowired
	public AuthorityCacheBean(AuthorityService authorityService) {
		super();
		this.authorityService = authorityService;
		if (logger.isDebugEnabled()) {
			logger.debug("AuthorityCacheBean init authorityService -- " + authorityService);
		}
		singleton = this;
	}

	@Override
	public Authority getAuthority(String authorityName) {
		if (authorities != null && authorities.size() > 0) {
			return authorities.get(authorityName);
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("getAuthority(): authorities is null!");
			}
		}
		return null;
	}

	@Override
	public void initAuthorities() {
		initBaseAuthorities();
	}

	/**
	 * 初始化authorities
	 */
	private synchronized void initBaseAuthorities() {
		if (authorityService == null) {
			if (logger.isErrorEnabled()) {
				logger.debug("AuthorityCacheBean isn't init by Spring.");
			}
			throw new IllegalArgumentException("AuthorityCacheBean isn't init by Spring.");
		}

		// 插叙数据库
		PageIndex pageIndex = new PageIndex();
		pageIndex.setMaxResult(AuthorityService.MAX_RESULT);
		List<Authority> mAuthorities = authorityService.query(null, pageIndex, null).getResultlist();
		if (mAuthorities != null && mAuthorities.size() > 0) {
			// 重新获取
			Map<String, Authority> nAuthorities = new HashMap<String, Authority>();
			for (Authority authority : mAuthorities) {
				if (authority.getAuthority() != null && !"".equals(authority.getAuthority())) {
					nAuthorities.put(authority.getAuthority(), authority);
				}
			}
			authorities = null;
			authorities = nAuthorities;
			configUrlMap = null;
			configUrlMap = new ConcurrentHashMap<String, List<ConfigAttribute>>();
			setConfigAttributes(nAuthorities.keySet());

			if (logger.isDebugEnabled()) {
				logger.debug("init authorities sucessfull :" + authorities);
			}
		}
	}

	static {
		// 定时器
		ThreadPoolUtil.scheduler.scheduleWithFixedDelay(new TimerTask() {
			@Override
			public void run() {
				try {
					AuthorityCacheBean.singleton.initBaseAuthorities();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 10, 60, TimeUnit.SECONDS);
	}

	public List<ConfigAttribute> getConfigAttributes() {
		return configAttributes;
	}

	/**
	 * 通过权限名称转化为权限系统的ConfigAttribute对象
	 * 
	 * @param attributeNames
	 */
	public void setConfigAttributes(Collection<String> attributeNames) {
		this.configAttributes = null;
		if (attributeNames != null) {
			this.configAttributes = SecurityConfig
					.createList(attributeNames.toArray(new String[attributeNames.size()]));
			if (logger.isDebugEnabled()) {
				logger.debug("init configAttributes sucessfull :" + configAttributes);
			}
		}
	}

	/**
	 * 根据URL和HttpMethod获取对应的权限
	 * 
	 * @return
	 */
	public List<ConfigAttribute> getLocalMatchConfigAttributes() {

		return getMatchConfigAttributes(InitFilter.getLocalURL(), HttpMethod.getHttpMethod(InitFilter.getLocalMethod()));
	}

	/**
	 * 根据URL和HttpMethod获取对应的权限
	 * 
	 * @param url
	 *            请求URL
	 * @param httpMethod
	 *            请求类型
	 * @return
	 */
	public List<ConfigAttribute> getMatchConfigAttributes(String url, HttpMethod httpMethod) {
		// 判断本地缓存是否已经存在此地址的匹配
		if (configUrlMap != null && configUrlMap.containsKey(url + httpMethod.toString())) {
			return configUrlMap.get(url + httpMethod.toString());
		}

		List<ConfigAttribute> mConfigAttributes = doGetMatchConfigAttributes(url, httpMethod);
		if (logger.isDebugEnabled()) {
			logger.debug("getMatchConfigAttributes : " + url + httpMethod.toString() + " not in cache get "
					+ mConfigAttributes);
		}
		configUrlMap.put(url + httpMethod.toString(), mConfigAttributes);

		return mConfigAttributes;
	}

	/**
	 * 根据URL获取对应的权限
	 * 
	 * @param url
	 *            请求URL
	 * @param httpMethod
	 *            请求类型
	 * @return
	 */
	private List<ConfigAttribute> doGetMatchConfigAttributes(String url, HttpMethod httpMethod) {
		if (authorities != null) {
			Map<String, Authority> attributeNames = new HashMap<String, Authority>();
			for (Authority authority : authorities.values()) {
				// 当前遍历权限是否匹配此地址
				if (authority.matchUrl(url) && authority.matchMethod(httpMethod)) {
					attributeNames.put(authority.getAuthority(), authority);
				}
			}
			return SecurityConfig.createList(attributeNames.keySet()
					.toArray(new String[attributeNames.keySet().size()]));
		}
		return null;
	}
}

4、改变投票策略为你所需要的方式

public class MyUnanimousBased extends UnanimousBased {
	public static final String USER_DEFAULT = "USER_DEFAULT";

	public MyUnanimousBased(List<AccessDecisionVoter> decisionVoters) {
		super(decisionVoters);
	}

	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes)
			throws AccessDeniedException {
		if (AuthorityCacheBean.singleton != null) {

			List<ConfigAttribute> configAttributes = AuthorityCacheBean.singleton.getLocalMatchConfigAttributes();
			if (logger.isDebugEnabled()) {
				logger.debug("removeRepeat(): old " + configAttributes + ", new: " + attributes);
			}

			if (configAttributes != null) {
				removeRepeat(configAttributes, attributes);
				attributes = configAttributes;
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("decide() getLocalMethod:" + InitFilter.getLocalMethod());
			logger.debug("decide() getLocalURL:" + InitFilter.getLocalURL());
			logger.debug("decide() authentication:" + authentication);
			logger.debug("decide() object:" + object);
			logger.debug("decide() attributes:" + attributes);
		}

		doDecide(authentication, object, attributes);
	}

	private void doDecide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
		int grant = 0;
		int abstain = 0;
		for (AccessDecisionVoter voter : getDecisionVoters()) {
			int result = voter.vote(authentication, object, attributes);

			if (logger.isDebugEnabled()) {
				logger.debug("Voter: " + voter + ", returned: " + result);
			}

			switch (result) {
			case AccessDecisionVoter.ACCESS_GRANTED:
				grant++;
				break;

			case AccessDecisionVoter.ACCESS_DENIED:
				throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
						"Access is denied"));

			default:
				abstain++;
				break;
			}
		}

		// To get this far, there were no deny votes
		if (grant > 0) {
			return;
		}
		// if (abstain > 0) {
		// return;
		// }

		// To get this far, every AccessDecisionVoter abstained
		checkAllowIfAllAbstainDecisions();
	}

	/**
	 * 去重
	 * 
	 * @param matchConfigAttributes
	 *            自定义匹配
	 * @param attributes
	 *            已有匹配
	 * @return
	 */
	private Collection<ConfigAttribute> removeRepeat(List<ConfigAttribute> matchConfigAttributes,
			Collection<ConfigAttribute> attributes) {
		if (matchConfigAttributes == null) {
			return attributes;
		}
		if (attributes != null) {
			for (ConfigAttribute attribute : attributes) {
				for (int i = 0; i < matchConfigAttributes.size(); i++) {
					ConfigAttribute mAttribute = matchConfigAttributes.get(i);
					if (mAttribute.getAttribute() != null && mAttribute.getAttribute().equals(attribute.getAttribute())) {
						matchConfigAttributes.remove(i);
						break;
					}
				}
			}
			matchConfigAttributes.addAll(attributes);
		}
		return matchConfigAttributes;
	}

}
如代码也就是在decide投票之前修改传入的attributes。

doDecide方法改变了投票方法:只需要当前访问所有匹配权限中有一条权限没有人投反对票且有人赞同,则用户可以通过。


5、拦截所有地址

因为我们修改的投票方式是需要满足至少一条权限通过即可通过,且由于权限加入阶段为投票阶段,默认Spring Security判断为若没有匹配到它指定方式的权限,不会走到投票阶段;也就是说,Spring Security自身若没有匹配到当前地址的权限,不会执行AccessDecisionManager。

所以我们在XML中加入了:

<!-- 如果需要进行数据库管理权限声明,必须设置本配置 -->
		<intercept-url pattern="/**" access="ADMIN_USER_DEFAULT" />

6、引入了p4jmvc

p4jmvc对基本的CURD Controller进行了封装,大大缩减的代码量,参考:《p4jmvc 内测版》 http://blog.csdn.net/partner4java/article/details/8759304


7、本架构借助了maven

分离了所有代码层,所以你会发现XML中的配置有classpath*:和classpath:两种,添加*会扫描所有jar。

主要jar为:p4jsecurity-1.0.0.jar、p4jmvc-1.0.0.jar、p4jorm-1.0.4.jar、p4jtools-1.0.0.jar。具体可参照源码


8、log

便于调试,加入了log,你需要做的就是类路径下存在log4j.xml文件,demo中已经加入


9、匿名用户

由于拦截了所有jsp,那么未登录用户如何访问登录界面呢?加入匿名用户权限

		<intercept-url pattern="/login.jsp*" access="LOGIN" />

		<anonymous username="guest" granted-authority="LOGIN" />

查看源码入口可从配置文件着手:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/security 
		http://www.springframework.org/schema/security/spring-security-3.1.xsd
	">

	<beans:import resource="classpath:META-INF/spring/authentication_manager.xml" />

	<!-- 权限判断方式 -->
	<beans:bean id="roleVoter"
		class="com.partner4java.security.access.vote.DefalutRoleVoter">
		<!-- 将只针对GROUP_为前缀的权限进行授权投票,默认为"ROLE_" -->
		<beans:property name="rolePrefix" value="*" />
	</beans:bean>
	<beans:bean id="authenticatedVoter"
		class="com.partner4java.security.access.vote.DefaultAuthenticatedVoter" />

	<beans:bean id="accessDecisionManager"
		class="com.partner4java.security.access.vote.MyUnanimousBased">
		<beans:constructor-arg name="decisionVoters">
			<beans:list>
				<beans:ref bean="roleVoter" />
				<beans:ref bean="authenticatedVoter" />
			</beans:list>
		</beans:constructor-arg>
	</beans:bean>

	<beans:bean id="loginUrlAuthenticationEntryPoint"
		class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
		<beans:constructor-arg value="/login.jsp" />
	</beans:bean>

	<beans:bean id="authenticationSuccessHandler"
		class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
		<beans:property name="defaultTargetUrl" value="/manage/index.do" />
	</beans:bean>

	<beans:bean id="authenticationFailureHandler"
		class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
		<beans:property name="defaultFailureUrl" value="/login.jsp?error=true" />
	</beans:bean>

	<!-- filter:前期拦截,初始化一些数据 -->
	<beans:bean id="webAuthenticationDetailsSource"
		class="com.partner4java.security.web.authentication.DefaultWebAuthenticationDetailsSource" />
	<beans:bean id="authenticationFilter"
		class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
		<!-- 用户登录信息资源获取类 -->
		<beans:property name="authenticationDetailsSource" ref="webAuthenticationDetailsSource" />
		<!-- 登录失败界面 -->
		<beans:property name="authenticationFailureHandler"
			ref="authenticationFailureHandler" />
		<!-- 登录成功界面 -->
		<beans:property name="authenticationSuccessHandler"
			ref="authenticationSuccessHandler" />
		<!-- 认证管理器 -->
		<beans:property name="authenticationManager" ref="authenticationManager" />
	</beans:bean>

	<http access-decision-manager-ref="accessDecisionManager"
		entry-point-ref="loginUrlAuthenticationEntryPoint">

		<intercept-url pattern="/login.jsp*" access="LOGIN" />

		<!-- 如果需要进行数据库管理权限声明,必须设置本配置 -->
		<intercept-url pattern="/**" access="ADMIN_USER_DEFAULT" />

		<anonymous username="guest" granted-authority="LOGIN" />

		<logout logout-success-url="/login.jsp" />
		<!-- <remember-me /> -->
		<custom-filter position="FORM_LOGIN_FILTER" ref="authenticationFilter" />
	</http>


	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="userDetailsService">
		</authentication-provider>
	</authentication-manager>


	<!-- 使用默认形式 -->
	<!-- <http auto-config="true"> <intercept-url pattern="/manage/index*" access="MANAGE_INDEX" 
		method="GET" /> <intercept-url pattern="/manage/authority/viewlist.do*" access="AUTH_VIEW" 
		method="POST" /> <intercept-url pattern="/manage/authority/*" access="AUTH_MANAGE" 
		/> <form-login login-page="/admin/login.jsp" default-target-url="/manage/index.do" 
		authentication-failure-url="/admin/login.jsp?error=true" /> <logout logout-success-url="/admin/login.jsp" 
		/> </http> -->
	<!-- <authentication-manager alias="daoAuthenticationProvider"> <authentication-provider> 
		<jdbc-user-service data-source-ref="dataSource" users-by-username-query="select 
		username,password,visible as enabled from Employee where username = ?" authorities-by-username-query="select 
		u.username,a.authority as authorities from employee u,Authority a,employee_authority 
		au where u.username = ? and u.EMPLOYEE_ID = au.EMPLOYEE_ID and a.AUTHORITY_ID 
		= au.AUTHORITY_ID" /> </authentication-provider> </authentication-manager> -->
</beans:beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/security 
		http://www.springframework.org/schema/security/spring-security-3.1.xsd
	">

	<!-- 通过默认的方式回去用户信息 -->
	<beans:bean id="userDetailsService"
		class="com.partner4java.security.core.userdetails.service.DefalutJdbcDaoImpl">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="usersByUsernameQuery">
			<beans:value>
				select username,password,visible as enabled from Employee where username = ? 
			</beans:value>
		</beans:property>
		<!-- <beans:property name="authoritiesByUsernameQuery">
			<beans:value>
				select u.username as username,a.authority as authority from employee u,Authority a,employee_authority au where u.username = ?  and u.EMPLOYEE_ID = au.EMPLOYEE_ID and a.AUTHORITY_ID = au.AUTHORITY_ID  and a.visible = 1  
			</beans:value>
		</beans:property> -->
		<beans:property name="employeeService" ref="employeeServiceBean"/>
	</beans:bean>
	<!-- 可以配置用户获取方式和密码加密方式 -->
	<beans:bean id="authenticationProvider"
		class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
		<beans:property name="userDetailsService" ref="userDetailsService" />
	</beans:bean>
	<!-- 认证管理器负责确定用户的身份,认证管理器由AuthenticationManager接口定义 -->
	<beans:bean id="authenticationManager"
		class="org.springframework.security.authentication.ProviderManager">
		<beans:constructor-arg name="providers">
			<!-- 他不依靠自己实现认证,而是逐一认证提供者的集合,直到某一个认证提供者能够成功的验证该用户的身份 -->
			<beans:list>
				<beans:ref bean="authenticationProvider" />
			</beans:list>
		</beans:constructor-arg>
	</beans:bean>
	
</beans:beans>


最后一个问题如何把P4jSecurity加入已有系统中?

只需要简单四步:

1、引入jar

p4jsecurity-1.0.0.jar、p4jmvc-1.0.0.jar、p4jorm-1.0.4.jar、p4jtools-1.0.0.jar、Spring相关jar具体可参考Demo

2、配置web.xml

contextConfigLocation加入classpath*:META-INF/spring/security.xml 

加入InitFilter、DelegatingFilterProxy两个Filter:

<?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:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name></display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<!-- "classpath*:"会扫描所有jar -->
		<param-value>
			classpath*:META-INF/spring/security.xml 
			classpath:META-INF/spring/datasource-c3p0.xml 
			classpath*:META-INF/spring/beans*.xml
		</param-value>
	</context-param>
	<context-param>
		<param-name>request.charsetencoding</param-name>
		<param-value>UTF-8</param-value>
	</context-param>

	<!-- 初始化一些参数资源等 -->
	<filter>
		<filter-name>initFilter</filter-name>
		<filter-class>com.partner4java.mvc.filter.InitFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>/manage/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>*.html</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>/j_spring_security_check</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>initFilter</filter-name>
		<url-pattern>/j_spring_security_logout</url-pattern>
	</filter-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- spring mvc配置 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
				classpath*:META-INF/spring/controller*.xml 
				classpath:META-INF/spring/cache.xml
			</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<!-- spring security安全配置 -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/manage/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/j_spring_security_check</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/j_spring_security_logout</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
3、导入相关表

employee、authority、employee_authority

4、加入jsp和样式文件


示例中还加入了ehcache,可参考。


C#的管理系统 用户权限菜单管理(1) &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;head&gt;    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;    &lt;meta name="viewport" content="width 阅读详情

相关推荐

二十、【用户管理与权限 - 篇二】前端交互:实现用户管理界面

一个功能完善的用户管理模块是任何后台系统的核心组成部分,它使得管理员能够有效地维护系统用户及其权限。

blues_C的博客 1131

AdminEx后台管理系统模板、用户权限管理设计、按钮级别

本人使用AdminEx模板来设计的用户权限管理系统界面。采用(Spring Boot、Apache Shiro、MyBatis、Thymeleaf)。项目简洁美观、优秀实用、功能强大,可扩展功能多。

weixin_48455733的博客 8473

权限管理demo以及表设计、精美后台页面html

自己写的权限管理demo,mysql数据库,以及数据表结构,静态页面在html文件下

Ace Admin后台管理系统模板、用户权限管理设计、按钮级别

Ace Admin是评价较高的一套UI框架,是一款轻量且功能丰富的管理模板,干净且易于使用,是一个基于Twitter bootstrap3开发的后台模板。

weixin_48455733的博客 5191

P4J:基于信息论的周期性时间序列分析工具

P4J 描述 P4J是一个python软件包,用于基于信息论目标函数对不规则采样和异方差时间序列进行周期检测。 P4J是为天文光曲线,恒星大小或通量的不规则采样时间序列开发的。 此程序包的核心是一个称为“周期图”的类,该类扫描周期/频率的数组以寻找使给定标准最大化的周期/频率。 这项工作的主要贡献是基于Cauchy-Schwarz二次互信息最大化的周期检测标准(Huijse et al。,2017)。 信息理论标准包含有关过程的整个概率密度函数的信息,并且比基于经典二阶统计量的标准更可靠(Principe,2010)。 为了进行比较,P4J还结合了天文学中使用的其他周期检测方法,例如相位分散最小化周期图(Stellingwerf,1973),拉夫勒-金曼弦长(Clarke,2002)和正交多谐波AoV周期图(Schwarzenberg-Czerny,1996)。 内容 光曲线的二次互信息周

从稳压管到LDO芯片:一张图看懂线性电源的‘内卷’进化史

本文追溯了从稳压管到LDO芯片的线性电源技术进化历程,详细解析了各阶段的技术突破与局限。重点探讨了现代LDO在超低功耗、高精度控制等方面的创新,并提供了实战选型的黄金法则,帮助工程师在电子设备小型化与低功耗化趋势中做出最优选择。

weixin_42525551的博客 213

菜单管理,权限管理,用户管理界面设计

提出问题! 1每个界面需要展示哪些问题?   1.1以哪种方式展示? 每个界面会进行哪些操作? 好了,带着问题进行思考,进行设计 。先来简单的用户管理界面来说,我需要展示用户(管理员)的信息。 方式是:表格形式,需要进行的是对用户的增加,删除,修改 ,模糊查询,以及赋予角色权限。 在菜单管理界面,我需要展示该用户所能操作的菜单详情,分别展示top 菜单 和top 菜单下的子菜单...

weixin_30500105的博客 3617

Claude Code 接入 DeepSeek-V4 教程

本文介绍Claude Code的安装配置流程:1) 安装Node.js 18+和Git(Windows);2) 通过npm全局安装@anthropic-ai/claude-code;3) 配置DeepSeek API环境变量(需替换API Key);4) 启动Claude Code或配置VSCode插件。重点包括Linux/macOS和Windows的环境变量设置方法,以及VSCode插件的settings.json配置项。完成配置后即可在终端或VSCode中使用Claude Code功能。

培根芝士的专栏 2036

B端系统:角色与权限界面设计,一文读懂。

角色与权限系统是一种用于管理和控制用户在系统中的访问和操作权限的机制。它通过将用户分配到不同的角色,并为每个角色分配相应的权限,来实现对系统资源的权限控制和管理。在角色与权限系统中,通常会定义多个角色,每个角色代表一组用户,具有相似的权限需求和操作范围。每个角色被赋予一组权限,这些权限决定了用户在系统中可以执行的操作和访问的资源。通过将用户分配到适当的角色,系统可以限制用户的权限范围,确保用户只能访问和操作其所需的资源。

2401_82943878的博客 1万+

SRAM故障排查实战:如何用Nano Prober定位6T存储单元的异常点

本文详细介绍了在SRAM故障排查中,如何运用Nano Prober(纳米探针)技术精准定位6T存储单元的内部异常。面对传统方法难以发现的电性参数漂移(如晶体管阈值电压偏移)或微小物理缺陷,Nano Prober能直接对单个6T单元内的晶体管进行I-V特性测量,结合失效模式分析,有效解决读写错误等疑难问题,是芯片失效分析的关键工具。

v5w6x的博客 673

使用 MATLAB/Simulink + Simscape Electrical + SimPowerSystems + Stateflow,构建一个多能互补微电网系统的动态响应仿真模型

本文详细介绍了使用MATLAB/Simulink构建多能互补微电网动态响应仿真模型的方法。文章从系统架构设计入手,包含光伏、风电、柴油发电机、锂电池储能等多种组件,重点讲解了建模过程、控制策略(下垂控制、PLL、SOC管理)和模式切换逻辑(Stateflow)。通过四种典型场景(负荷突增、光伏出力骤降、并网/孤岛切换、电动机启动)的仿真分析,验证了微电网在动态响应中的关键性能指标,并提出了高可靠性设计建议。该模型为微电网的稳定性分析和优化设计提供了有效工具,特别强调了储能系统在快速功率支撑中的重要作用。

amy_mhd的博客 164

H5 Admin后台管理系统、用户权限管理设计、按钮级别、数据级别、html+bootstrap后台管理前端界面设计

一个高颜值后台管理模板,Light Year Admin后台管理系统模板是一个基于Bootstrap v3.3.7的纯HTML模板,目前也已经更新了基于Bootstrap 4.4.1的版本。都有iframe以及非iframe的两种不同的形式供大家选择使用。简洁而清新的后台模板,功能虽少,倒也满足简单的后台功能,也能够快速上手。Bootstrap 3是一个强大的前端框架,具备响应式设计、栅格系统、丰富的CSS组件和JavaScript插件等特点。

weixin_48455733的博客 8021

openclaw通俗入门系列9——流式传输 + 分块

流式传输 = 不等写完就开始发。分块流式传输是把长回复切成几条消息发(所有渠道),草稿流式传输是像打字一样实时显示(仅 Telegram)。可以配置块大小、发送时机、合并规则、类人延迟。

m0_60605453的博客 510

转转统一权限系统的设计与实现(设计篇)

去年底转转启动建设统一权限管理系统,到今天公司大部分业务系统都已经用上了。本系列将会分为三部分来分享下转转新权限系统的设计与实现。今天先分享第一部分设计篇,后续还将分享后端架构和前端架构部分。.........

zhuanzhuantech的博客 2033

华为OD机考2025C卷 - 精准核酸检测(Java & Python& JS & C++ & C语言)

华为OD机考2025C卷 - 精准核酸检测,提供在线OJ Java & Python& JS & C++ & C

算法大师! 2892

JavaScript教程-字符集,Unicode转义序列,标识符,数据类型,数字,未定义值,浮点数,字符串,引用数据类型,类型检测,类型转换,运算符,关系运算符,

前端学习

VAN 214

SaToken学习笔记-04

#SaToken学习笔记-04 如果有问题,请点击:传送门 ##角色认证 在sa-token中,角色和权限可以独立验证 // 当前账号是否含有指定角色标识, 返回true或false StpUtil.hasRole("super-admin"); // 当前账号是否含有指定角色标识, 如果验证未通过,则抛出异常: NotRoleException StpUtil.checkRole("super-admin"); // 当前账号是否含有指定角色标识 [指定多个,必须全

qq_47815451的博客 820

OpenClaw实战系列01:OpenClaw接入飞书机器人全接入指南 + Ollama本地大模型

通过 OpenClaw + Ollama + 飞书的组合,我们成功搭建了一个完全私有、免费、可定制的AI助理。它不仅能在日常聊天中提供帮助,还能通过OpenClaw强大的“技能”体系,真正去操作你的电脑、管理文件、甚至执行代码。这套方案将数据留在本地,既保证了隐私安全,又锻炼了动手能力。现在,去给你的AI助理添加更多酷炫的技能吧!

PeterPan的博客 1万+

深入分析Java ClassLoader原理

一、什么是ClassLoader? 大家都知道,当我们写好一个Java程序之后,不是管是CS还是BS应用,都是由若干个.class文件组织而成的一个完整的Java应用程序,当程序在运行时,即会调用该程序的一个入口函数来调用系统的相关功能,而这些功能都被封装在不同的class文件当中,所以经常要从这个class文件中要调用另外一个class文件中的方法,如果另外一个文件不...

weixin_30407613的博客 1120

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

odoo12 用户(users) 权限管理界面分析

起因: 由于需要了解 odoo的权限管理,去看了下 odoo 是如何给用户赋权限的。发现好多不能理解。因此,打算从 user 的xml开始。看里面到底是什么意思 第一步,肯定查看user的xml。找user源码 odoo/odoo/addons/base/views/res_users_views.xml <record id="view_users_form" model="...

1428

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Vue + ElementUI 手撸后台管理网站基本框架(二)权限控制

前端权限控制的本质 权限策略 接口权限控制 页面级访问权限控制 创建路由表 Mock权限列表数据 编写导航钩子 数据级操作权限控制 路由控制完整流程图 NEXT——登录及系统菜单加载 源码 本系列目录 前端权限控制的本质 在管理系统中,感觉最让新手们搞不懂就是权限管理这部份了,而这也是后台管理系统中最基础的部分。 一般说来,权限管理可以分为两种情况:第一种为页面级访问...

harsima的博客 11万+

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

p4jmvc 内测版

(声明:目前p4jmvc内测版只支持Spring MVC,仅作各位技术参考。) 附件源码下载地址:http://download.csdn.net/detail/partner4java/5220557 作用:简化Controller,常用的CURD操作,Controller不需要写一行代码,只需要继承即可。 注意: p4jmvc主要借助了p4jorm。 如:我们对城市管理的Control...

runfeel 184

SpringMVC + Shiro通过注解配置的权限未生效

描述:登录后通过注解配置的权限未生效,不是要求角色的用户也能访问此页面 分析可能原因:授权注解未生效 最终解决方案: Spring-shiro.xml使用下面的配置开启注解: <!--Shiro生命周期处理器--> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProces

Excaliburace的博客 2532

Spring AOP事务管理(使用切面把事务管理起来)

在《Spring Transaction 分析事务属性(事务的基本概念、配置)》基础上  1、使用基于注解的AOP事务管理      探索tx:annotation-driven标签:  标签是注解驱动的事务管理支持的核心。  标签的属性:  transaction-manager:指定到现有的PlatformTransactionManager bean的引

java相关技术(partner4java专栏)希望对您的学习有所帮助 6万+

Spring 实现你自己的事务同步

在《Spring Transaction 分析事务属性(事务的基本概念、配置)》基础上  将介绍如何实现你自己的事务同步,只要是活动的事务状态发生变化就会收到TransactionSynchronizationManager的回调。  书中的demo:  使用TransactionSynchronizationManager注册了TransactionSynchronizat

java相关技术(partner4java专栏)希望对您的学习有所帮助 2万+
上一篇: 《partner4java 讲述Spring入门》之:spring cache支持(spring3.1如何使用cache 缓存)
下一篇: p4jmvc 内测版
partner4java
博客等级 码龄17年 481粉丝 183原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址