创建数据库
3.bean.xml springApplication的配置
4.spring-security.xml配置
下面看看java代码吧
6.MyAccessDecisionManager.java
7.MySecurityMetadataSource.java这个类会在项目启动时,加载所有权限和资源对象关系
9.MyUserDetailServiceImpl.java
/*
Navicat MySQL Data Transfer
Source Server : mysql3306
Source Server Version : 50542
Source Host : localhost:3306
Source Database : db_security
Target Server Type : MYSQL
Target Server Version : 50542
File Encoding : 65001
Date: 2015-11-09 21:36:21
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for authorities
-- ----------------------------
DROP TABLE IF EXISTS `authorities`;
CREATE TABLE `authorities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`authority` varchar(20) DEFAULT NULL,
`uid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of authorities
-- ----------------------------
INSERT INTO `authorities` VALUES ('1', 'ROLE_ADMIN', '1');
INSERT INTO `authorities` VALUES ('2', 'ROLE_USER', '2');
INSERT INTO `authorities` VALUES ('3', 'ROLE_USER', '1');
-- ----------------------------
-- Table structure for resources
-- ----------------------------
DROP TABLE IF EXISTS `resources`;
CREATE TABLE `resources` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`resource_name` varchar(100) NOT NULL,
`resource_type` varchar(100) NOT NULL,
`resource_content` varchar(200) NOT NULL,
`resource_desc` varchar(200) NOT NULL,
`enabled` int(2) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `resource_name` (`resource_name`),
KEY `resource_name_2` (`resource_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of resources
-- ----------------------------
INSERT INTO `resources` VALUES ('1', '管理员资源', 'requesturl', '/auth/login', '进入管理员页面', '1');
INSERT INTO `resources` VALUES ('2', '普通用户', 'requesturl', '/index.jsp', '登录首页', '1');
-- ----------------------------
-- Table structure for resource_authority
-- ----------------------------
DROP TABLE IF EXISTS `resource_authority`;
CREATE TABLE `resource_authority` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rid` int(11) DEFAULT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of resource_authority
-- ----------------------------
INSERT INTO `resource_authority` VALUES ('1', '1', '1');
INSERT INTO `resource_authority` VALUES ('2', '2', '1');
INSERT INTO `resource_authority` VALUES ('3', '2', '2');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rolename` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'ROLE_ADMIN');
INSERT INTO `role` VALUES ('2', 'ROLE_USER');
-- ----------------------------
-- Table structure for role_user
-- ----------------------------
DROP TABLE IF EXISTS `role_user`;
CREATE TABLE `role_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`enable` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role_user
-- ----------------------------
INSERT INTO `role_user` VALUES ('1', '1', '1', '1');
INSERT INTO `role_user` VALUES ('2', '2', '1', '1');
INSERT INTO `role_user` VALUES ('3', '2', '2', '1');
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(60) DEFAULT NULL,
`enabled` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3', '0');
INSERT INTO `users` VALUES ('2', 'user', '21232f297a57a5a743894a0e4a801fc3', '0');
2.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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>shetest</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>shetest.root</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/beans.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security会话控制 -->
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- SpringSecurity必须的filter -->
<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>/*</url-pattern>
</filter-mapping>
<!-- springMVC -->
<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*:config/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- SpringMVC 字符编码过滤 -->
<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>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.bean.xml springApplication的配置
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.webo" />
<import resource="spring-security.xml"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath*:config/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- org.springframework.orm.hibernate4.LocalSessionFactoryBean org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.webo.entity.*</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<!-- org.springframework.orm.hibernate4.HibernateTransactionManager org.springframework.orm.hibernate3.HibernateTransactionManager"> -->
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * com.webo.service..*.*(..))" />
<aop:advisor pointcut-ref="bussinessService"
advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="query*" read-only="true" />
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
4.spring-security.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:security="http://www.springframework.org/schema/security"
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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:global-method-security pre-post-annotations="enabled" />
<!-- 不需要拦截的请求 -->
<security:http pattern="/login.jsp" security="none"/>
<security:http auto-config="true">
<security:form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?error=true"
always-use-default-target="true"
default-target-url="/index.jsp"/>
<!-- <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
<security:intercept-url pattern="/jsp/**" access="ROLE_USER,ROLE_ADMIN"/> -->
<security:logout logout-success-url="/login.jsp"/>
<security:access-denied-handler error-page="/accessDenied.jsp"/>
<!-- 会话管理配置 -->
<security:session-management invalid-session-url="/login.jsp">
<security:concurrency-control max-sessions="1"/>
</security:session-management>
<security:custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</security:http>
<bean id="mySecurityMetadataSource" class="com.webo.filter.MySecurityMetadataSource">
</bean>
<!-- 配置认证管理器 -->
<security:authentication-manager alias="myAuthenticationManager">
<security:authentication-provider ref="authenticationProvider"></security:authentication-provider>
</security:authentication-manager>
<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userdetailService" />
<!--显示用户错误信息-->
<property name="hideUserNotFoundExceptions" value="false" />
<property name="passwordEncoder" ref="md5password"></property>
</bean>
<!-- <bean id="userService" class="com.webo.service.impl.UserServiceImpl"/> -->
<bean name="userdetailService" class="com.webo.filter.MyAuthenticationManager">
<!-- <property name="userService" ref="userService"></property> -->
</bean>
<bean id="myAccessDecisionManager" class="com.webo.filter.MyAccessDecisionManager"></bean>
<bean name="securityFilter" class="com.webo.filter.MySecurityFilter">
<!-- 用户拥有的权限 -->
<property name="authenticationManager" ref="myAuthenticationManager" />
<!-- 用户是否拥有所请求资源的权限 -->
<property name="accessDecisionManager" ref="myAccessDecisionManager" />
<!-- 资源与权限对应关系 -->
<property name="securityMetadataSource" ref="mySecurityMetadataSource" />
</bean>
<!-- 密码加密策略 -->
<bean name="md5password" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
</bean>
<!-- 指定提示信息 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:config/message_zh_CN"></property>
</bean>
</beans>
下面看看java代码吧
5.MySecurityFilter.java
package com.webo.filter;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
//与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,
//其他的两个组件,已经在AbstractSecurityInterceptor定义
private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
private static int a;
private void invoke(FilterInvocation fi) throws IOException, ServletException {
System.out.println("用户发送请求! "+(a++));
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
}
@Resource
public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
public void init(FilterConfig arg0) throws ServletException {
}
public void destroy() {
}
@Override
public Class<? extends Object> getSecureObjectClass() {
//下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
return FilterInvocation.class;
}
}
6.MyAccessDecisionManager.java
package com.webo.filter;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
//3
public class MyAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes == null) {
return;
}
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator<ConfigAttribute> iterator = configAttributes.iterator();
while(iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
System.out.println("needPermission is " + needPermission);
//用户所拥有的权限authentication
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needPermission.contains((ga.getAuthority()))) {
return;
}
}
}
//没有权限让我们去捕捉
throw new AccessDeniedException(" 没有权限访问!");
}
public boolean supports(ConfigAttribute attribute) {
return true;
}
public boolean supports(Class<?> clazz) {
return true;
}
}
7.MySecurityMetadataSource.java这个类会在项目启动时,加载所有权限和资源对象关系
package com.webo.filter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import com.webo.entity.Authorities;
import com.webo.entity.ResAndAuth;
import com.webo.entity.Resources;
import com.webo.service.AuthoritiesService;
import com.webo.service.ResAndAuthService;
import com.webo.service.ResourceService;
//1 加载资源与权限的对应关系
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private AuthoritiesService authService;
private ResourceService resService;
private ResAndAuthService resAndAuthService;
//由spring调用
/*public MySecurityMetadataSource(AuthoritiesService authService, ResourceService resService, ResAndAuthService resAndAuthService) throws Exception {
this.authService = authService;
this.resService = resService;
this.resAndAuthService = resAndAuthService;
//initResources();
}
public MySecurityMetadataSource(){
initResources();
}*/
// 资源
private static HashMap<String, Collection<ConfigAttribute>> requestMap;//new HashMap<RequestMatcher, Collection<ConfigAttribute>>();
// 权限 ROLE_USER,ROLE_ADMIN
private static Collection<ConfigAttribute> allAuthAttribute;// = new HashSet<ConfigAttribute>();
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return new ArrayList<ConfigAttribute>();
}
/**
* 返回所请求资源所需要的权限
* @return 返回资源所对应的权限list
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object)
throws IllegalArgumentException {
// 把对象转化为请求
final HttpServletRequest request = ((FilterInvocation) object).getRequest();
// 循环整个Map 看看有没有可以匹配的,如果有匹配的就立刻返回
if(requestMap == null){
initResources();
}
String uri = request.getRequestURI();
String url = request.getRequestURL().toString();
String servleturl = request.getServletPath();
return requestMap.get(servleturl);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
/**
* 初始化所有的资源,这个会在容器运行的时候的构造方法里调用
*/
private void initResources() {
// 读取所有的资源,和资源相关联的的权限
// 读取所有权限点
requestMap = new HashMap<String, Collection<ConfigAttribute>>();
allAuthAttribute = new HashSet<ConfigAttribute>();
Collection<Authorities> allAuthority = authService.queryAllAuth();
for (Authorities auth : allAuthority) {
String authString = auth.getAuthority(); //ROLE_USER,ROLE_ADMIN
ConfigAttribute attrConfig = new SecurityConfig(authString);
allAuthAttribute.add(attrConfig);
}
// 读取所有资源
Collection<Resources> allResources = resService.queryAllRes();
// 循环所有资源
for (Resources res : allResources) {
// 按照资源查询和资源相关的权限点
Collection<ResAndAuth> authEntities = resAndAuthService.queryAuth(res.getId()+"");
// 把此关系保存到requestMap里
// 获取资源
String resourceContent = res.getContent(); //资源的请求路径 /admin/*,/user/*
// 把url资源转化为一个spring的工具类,请求匹配器类
// 循环权限 定义一个权限的集合,和此资源对应起来,添加到HashMap里
Collection<ConfigAttribute> array = new ArrayList<ConfigAttribute>();
for (ResAndAuth auth : authEntities) {
Authorities a = authService.queryAuthById(auth.getAid()+"");
// 转化权限对象为SecurityConfig
ConfigAttribute securityConfig = new SecurityConfig(a.getAuthority());
array.add(securityConfig);
}
requestMap.put(resourceContent, array);
}
}
public AuthoritiesService getAuthService() {
return authService;
}
@Resource
public void setAuthService(AuthoritiesService authService) {
this.authService = authService;
}
public ResourceService getResService() {
return resService;
}
@Resource
public void setResService(ResourceService resService) {
this.resService = resService;
}
public ResAndAuthService getResAndAuthService() {
return resAndAuthService;
}
@Resource
public void setResAndAuthService(ResAndAuthService resAndAuthService) {
this.resAndAuthService = resAndAuthService;
}
}
8.MyAuthenticationManager.java
package com.webo.filter;
import java.util.Collection;
import java.util.HashSet;
import javax.annotation.Resource;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.webo.entity.Authorities;
import com.webo.entity.User;
import com.webo.entity.UserEntity;
import com.webo.service.AuthoritiesService;
import com.webo.service.UserService;
import com.webo.util.StringUtils;
@Component
public class MyAuthenticationManager implements UserDetailsService {
private UserService userService;
private AuthoritiesService authService;
@Resource
public void setUserService(UserService userService) {
this.userService = userService;
}
@Resource
public void setAuthService(AuthoritiesService authService) {
this.authService = authService;
}
@Override
public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
if(StringUtils.isEmpty(id)){
throw new UsernameNotFoundException("用户名不能为空!");
}
User user = userService.queryUserByName(id);
if (user == null) {
throw new UsernameNotFoundException("用户名或密码错误!");
}
Collection<Authorities> userAuths = authService.queryAuthByUId(user.getId()+"");
Collection<ConfigAttribute> userAuthsAttribute = new HashSet<ConfigAttribute>();
for (Authorities auth : userAuths) {
String authString = auth.getAuthority(); //ROLE_USER,ROLE_ADMIN
ConfigAttribute attrConfig = new SecurityConfig(authString);
userAuthsAttribute.add(attrConfig);
}
UserEntity userDetail = new UserEntity(user.getId(), user.getUsername(), user.getPassword(), user.getEnabled(), userAuthsAttribute);
return userDetail;
}
}
9.MyUserDetailServiceImpl.java
package com.webo.filter;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.webo.entity.Authorities;
import com.webo.entity.UserEntity;
import com.webo.service.AuthoritiesService;
import com.webo.service.UserService;
public class MyUserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private AuthoritiesService authService;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// 读取用户
UserEntity userEntity = userService.queryUserByName(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}else {
if(userEntity.getEnabled().intValue() == 1){
throw new UsernameNotFoundException("该用户处于锁定状态");
}
}
// 读取权限
Collection<ConfigAttribute> auths = new ArrayList<ConfigAttribute>();
// 这里需要从数据库里读取所有的权限点
Collection<Authorities> aes = authService.queryAuthByUId(userEntity.getId()+"");
for (Authorities auth : aes) {
ConfigAttribute attrConfig = new SecurityConfig(auth.getAuthority());
auths.add(attrConfig);
}
UserEntity user = new UserEntity(userEntity.getId(), userEntity.getUsername(),
userEntity.getPassword(), userEntity.getEnabled(), auths);
return user;
}
}
10.service dao 设计