创建数据库

/*
Navicat MySQL Data TransferSource Server         : mysql3306
Source Server Version : 50542
Source Host           : localhost:3306
Source Database       : db_securityTarget Server Type    : MYSQL
Target Server Version : 50542
File Encoding         : 65001Date: 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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://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.xsdhttp://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;  }  @Resourcepublic 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_ADMINprivate static Collection<ConfigAttribute> allAuthAttribute;// = new HashSet<ConfigAttribute>();@Overridepublic Collection<ConfigAttribute> getAllConfigAttributes() {return new ArrayList<ConfigAttribute>();}/*** 返回所请求资源所需要的权限* @return 返回资源所对应的权限list*/@Overridepublic 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);}@Overridepublic 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_ADMINConfigAttribute 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()+"");// 转化权限对象为SecurityConfigConfigAttribute securityConfig = new SecurityConfig(a.getAuthority());array.add(securityConfig);}requestMap.put(resourceContent, array);}}public AuthoritiesService getAuthService() {return authService;}@Resourcepublic void setAuthService(AuthoritiesService authService) {this.authService = authService;}public ResourceService getResService() {return resService;}@Resourcepublic void setResService(ResourceService resService) {this.resService = resService;}public ResAndAuthService getResAndAuthService() {return resAndAuthService;}@Resourcepublic 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;@Resourcepublic void setUserService(UserService userService) {this.userService = userService;}@Resourcepublic 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_ADMINConfigAttribute 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 {@Autowiredprivate UserService userService;@Autowiredprivate AuthoritiesService authService;@Overridepublic 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 设计

spring security基于数据库的安全认证 配置相关推荐

  1. Spring Security基于数据库认证用户登录

    Spring Security为我们提供了默认的登录页面,通过重写以AuthenticationManagerBuilder为参数的configure方法,我们可基于各种数据存储来认证用户,比如内存. ...

  2. Spring Security 基于数据库的认证

    介绍 之前使用的全是基于内存的认证,这里使用基于数据库的认证. 设计数据表 这里设计数据表 创建项目 这里使用Mybatis作为项目. 添加如下依赖 添加driud连接池依赖 <dependen ...

  3. 实现账号在一端登入_跟我学spring security 基于数据库实现一个基本的登入登出...

    第一章我们基于内存中的用户信息实现了一个基本的登入功能,不过实际的项目中用户信息一般都是存在数据库中的.本章我们来实现一个比较接近真实项目的登入登出,同时引入UserDetailsService的概念 ...

  4. Spring Security Oauth2 JWT 实现用户认证授权功能

    Spring Security Oauth2 JWT 一 用户认证授权 1. 需求分析 1.1 用户认证与授权 什么是用户身份认证? 用户身份认证即用户去访问系统资源时系统要求验证用户的身份信息,身份 ...

  5. Spring Security 实战:使用 JWT 认证访问接口

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 1. 前言 欢迎阅读Spring Security 实战 ...

  6. Spring Security and Angular 实现用户认证

    引言 度过了前端框架的技术选型之后,新系统起步. ng-alain,一款功能强大的前端框架,设计得很好,两大缺点,文档不详尽,框架代码不规范. 写前台拦截器的时候是在花了大约半小时的时间对代码进行全面 ...

  7. spring security:基于MongoDB的认证

    spring security对基于数据库的认证支持仅限于JDBC,而很多项目并非使用JDBC,比如Nosql数据库很多使用的是 Mongo Java Driver,这样就无法用默认的<jdbc ...

  8. Spring Security使用数据库登录认证授权

    一.搭建项目环境 1.创建 RBAC五张表 RBAC,即基于角色的权限访问控制(Role-Based Access Control),就是用户通过角色与权限进行关联. 在这种模型中,用户与角色之间,角 ...

  9. security基于数据库的认证(二)

    @TOC 前言:在security初体验(一)里,用户名和密码的认证都是基于内存级别的,本章主要是说security如何从db里取用户名和密码来验证的. 1.准备的sql DROP TABLE IF ...

最新文章

  1. 研发管理101军规#003 实战规模化敏捷:从8人到百人的敏捷之路
  2. 谷歌花35元就“骗”走刷脸数据:黑人为主,霸王条款无限使用,为强化新手机能力...
  3. VS2013安装MVC5
  4. 综合-某假期欢乐赛 (Apri, 2018)
  5. 【Matlab 图像】开闭运算 imopen imclose
  6. [原]零基础学习在Android进行SDL开发系列文章
  7. 位移运算符(7个)之第一个: 左移
  8. insert into select 主键自增_springboot2结合mybatis拦截器实现主键自动生成
  9. Android QQ登录 程序奔溃的问题
  10. antdesign 柱状图_以Ant Design为例:看B端设计的基本套路
  11. python得安什么安装包_初学 Python 需要安装哪些软件?
  12. 辰视携最新3D视觉技术及解决方案参加华南工博会国际机器视觉展
  13. matlab如何求有约束最优化最大值,6.4.2有约束最优化问题的求解-东北大学数学系.ppt...
  14. STI、LOD与WPE概念:形成机理及对电路设计的影响
  15. Java设计模式面试题
  16. matlab曲线拟合工具箱cftool
  17. thinkphp5.1使用云之讯
  18. 【LeetCode】606.根据二叉树创建字符串
  19. PC服务器硬盘故障处理
  20. C++ tuple的介绍及使用

热门文章

  1. python3将base64格式的图片保存为MD5值的图片
  2. magic-api的使用体验
  3. 读书笔记:《启示录》
  4. 在wsl的图形化界面中无法启动没有管理权限的“synaptic软件包管理器”
  5. bert 环境搭建之PytorchTransformer 安装
  6. 二、Apollo高精地图详解(3.Apollo地图采集和生产)
  7. NLP经典论文:Word2vec、CBOW、Skip-gram 笔记
  8. 翻译连载 | JavaScript轻量级函数式编程-第4章:组合函数 |《你不知道的JS》姊妹篇
  9. 译码阻塞和死锁的等待资源
  10. 新浪云php与微信,新浪SAE php能够获取微信的头像,但是在本地运行代码获取不到?...