项目GitHub地址 :

https://github.com/FrameReserve/TrainingBoot

Spring Boot (三)集成spring security,标记地址:

https://github.com/FrameReserve/TrainingBoot/releases/tag/0.0.3

pom.xml

只列举 Spring Security配置,完整配置请查看Git项目地址

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  4. <java.version>1.8</java.version>
  5. <!--  依赖版本  -->
  6. <mybatis.version>3.4.1</mybatis.version>
  7. <mybatis.spring.version>1.3.0</mybatis.spring.version>
  8. <spring-security.version>4.1.0.RELEASE</spring-security.version>
  9. </properties>
  10. <!-- spring security -->
  11. <dependency>
  12. <groupId>org.springframework.security</groupId>
  13. <artifactId>spring-security-web</artifactId>
  14. <version>${spring-security.version}</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.security</groupId>
  18. <artifactId>spring-security-config</artifactId>
  19. <version>${spring-security.version}</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.security</groupId>
  23. <artifactId>spring-security-taglibs</artifactId>
  24. <version>${spring-security.version}</version>
  25. </dependency>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- 依赖版本 -->
<mybatis.version>3.4.1</mybatis.version>
<mybatis.spring.version>1.3.0</mybatis.spring.version>
	&lt;spring-security.version&gt;4.1.0.RELEASE&lt;/spring-security.version&gt;
&lt;/properties&gt;

<!-- spring security -->

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-web</artifactId>

            <version>${spring-security.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-config</artifactId>

            <version>${spring-security.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-taglibs</artifactId>

            <version>${spring-security.version}</version>

        </dependency>

Spring Security 配置类:

src/main/java/com/training/core/security/WebSecurityConfig.java

  1. package com.training.core.security;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.security.access.AccessDecisionManager;
  9. import org.springframework.security.access.AccessDecisionVoter;
  10. import org.springframework.security.access.vote.AuthenticatedVoter;
  11. import org.springframework.security.access.vote.RoleVoter;
  12. import org.springframework.security.authentication.AuthenticationManager;
  13. import org.springframework.security.authentication.event.LoggerListener;
  14. import org.springframework.security.config.annotation.ObjectPostProcessor;
  15. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  16. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  17. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  18. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  19. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  20. import org.springframework.security.core.userdetails.UserDetailsService;
  21. import org.springframework.security.web.access.AccessDeniedHandler;
  22. import org.springframework.security.web.access.AccessDeniedHandlerImpl;
  23. import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
  24. import org.springframework.security.web.access.expression.WebExpressionVoter;
  25. import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
  26. import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
  27. import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
  28. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  29. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  30. import com.training.sysmanager.service.AclResourcesService;
  31. import com.training.sysmanager.service.impl.AclResourcesServiceImpl;
  32. /**
  33. * Created by Athos on 2016-10-16.
  34. */
  35. @Configuration
  36. @EnableWebSecurity
  37. @EnableGlobalMethodSecurity(prePostEnabled = true)
  38. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  39. @Resource
  40. private UserDetailsService userDetailsService;
  41. @Resource
  42. private MySecurityMetadataSource mySecurityMetadataSource;
  43. @Override
  44. protected void configure(HttpSecurity http) throws Exception {
  45. http.addFilterAfter(MyUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  46. // 开启默认登录页面
  47. http.authorizeRequests().anyRequest().authenticated().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
  48. public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
  49. fsi.setSecurityMetadataSource(mySecurityMetadataSource);
  50. fsi.setAccessDecisionManager(accessDecisionManager());
  51. fsi.setAuthenticationManager(authenticationManagerBean());
  52. return fsi;
  53. }
  54. }).and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login.html")).and().logout().logoutSuccessUrl("/index.html").permitAll();
  55. // 自定义accessDecisionManager访问控制器,并开启表达式语言
  56. http.exceptionHandling().accessDeniedHandler(accessDeniedHandler()).and().authorizeRequests().anyRequest().authenticated().expressionHandler(webSecurityExpressionHandler());
  57. // 自定义登录页面
  58. http.csrf().disable();
  59. // 自定义注销
  60. // http.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
  61. // .invalidateHttpSession(true);
  62. // session管理
  63. http.sessionManagement().maximumSessions(1);
  64. // RemeberMe
  65. // http.rememberMe().key("webmvc#FD637E6D9C0F1A5A67082AF56CE32485");
  66. }
  67. @Override
  68. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  69. // 自定义UserDetailsService
  70. auth.userDetailsService(userDetailsService);
  71. }
  72. @Bean
  73. UsernamePasswordAuthenticationFilter MyUsernamePasswordAuthenticationFilter() {
  74. UsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter = new UsernamePasswordAuthenticationFilter();
  75. myUsernamePasswordAuthenticationFilter.setPostOnly(true);
  76. myUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
  77. myUsernamePasswordAuthenticationFilter.setUsernameParameter("name_key");
  78. myUsernamePasswordAuthenticationFilter.setPasswordParameter("pwd_key");
  79. myUsernamePasswordAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
  80. myUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(simpleUrlAuthenticationFailureHandler());
  81. return myUsernamePasswordAuthenticationFilter;
  82. }
  83. @Bean
  84. AccessDeniedHandler accessDeniedHandler() {
  85. AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl();
  86. accessDeniedHandler.setErrorPage("/securityException/accessDenied");
  87. return accessDeniedHandler;
  88. }
  89. @Bean
  90. public LoggerListener loggerListener() {
  91. System.out.println("org.springframework.security.authentication.event.LoggerListener");
  92. return new LoggerListener();
  93. }
  94. @Bean
  95. public org.springframework.security.access.event.LoggerListener eventLoggerListener() {
  96. System.out.println("org.springframework.security.access.event.LoggerListener");
  97. return new org.springframework.security.access.event.LoggerListener();
  98. }
  99. /*
  100. *
  101. * 这里可以增加自定义的投票器
  102. */
  103. @Bean(name = "accessDecisionManager")
  104. public AccessDecisionManager accessDecisionManager() {
  105. List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList();
  106. decisionVoters.add(new RoleVoter());
  107. decisionVoters.add(new AuthenticatedVoter());
  108. decisionVoters.add(webExpressionVoter());// 启用表达式投票器
  109. MyAccessDecisionManager accessDecisionManager = new MyAccessDecisionManager(decisionVoters);
  110. return accessDecisionManager;
  111. }
  112. @Bean(name = "authenticationManager")
  113. @Override
  114. public AuthenticationManager authenticationManagerBean() {
  115. AuthenticationManager authenticationManager = null;
  116. try {
  117. authenticationManager = super.authenticationManagerBean();
  118. } catch (Exception e) {
  119. e.printStackTrace();
  120. }
  121. return authenticationManager;
  122. }
  123. @Bean(name = "failureHandler")
  124. public SimpleUrlAuthenticationFailureHandler simpleUrlAuthenticationFailureHandler() {
  125. return new SimpleUrlAuthenticationFailureHandler("/getLoginError");
  126. }
  127. @Bean(name = "aclResourcesService")
  128. @ConditionalOnMissingBean
  129. public AclResourcesService aclResourcesService() {
  130. return new AclResourcesServiceImpl();
  131. }
  132. /*
  133. * 表达式控制器
  134. */
  135. @Bean(name = "expressionHandler")
  136. public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
  137. DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
  138. return webSecurityExpressionHandler;
  139. }
  140. /*
  141. * 表达式投票器
  142. */
  143. @Bean(name = "expressionVoter")
  144. public WebExpressionVoter webExpressionVoter() {
  145. WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
  146. webExpressionVoter.setExpressionHandler(webSecurityExpressionHandler());
  147. return webExpressionVoter;
  148. }
  149. }
package com.training.core.security;

import java.util.ArrayList;

import java.util.List; import javax.annotation.Resource; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.access.AccessDecisionManager;

import org.springframework.security.access.AccessDecisionVoter;

import org.springframework.security.access.vote.AuthenticatedVoter;

import org.springframework.security.access.vote.RoleVoter;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.event.LoggerListener;

import org.springframework.security.config.annotation.ObjectPostProcessor;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.web.access.AccessDeniedHandler;

import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

import org.springframework.security.web.access.expression.WebExpressionVoter;

import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.training.sysmanager.service.AclResourcesService;

import com.training.sysmanager.service.impl.AclResourcesServiceImpl; /**
  • Created by Athos on 2016-10-16.

    */

    @Configuration

    @EnableWebSecurity

    @EnableGlobalMethodSecurity(prePostEnabled = true)

    public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Resource

    private UserDetailsService userDetailsService; @Resource

    private MySecurityMetadataSource mySecurityMetadataSource; @Override

    protected void configure(HttpSecurity http) throws Exception {
     http.addFilterAfter(MyUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    // 开启默认登录页面
    http.authorizeRequests().anyRequest().authenticated().withObjectPostProcessor(new ObjectPostProcessor&lt;FilterSecurityInterceptor&gt;() {
    public &lt;O extends FilterSecurityInterceptor&gt; O postProcess(O fsi) {
    fsi.setSecurityMetadataSource(mySecurityMetadataSource);
    fsi.setAccessDecisionManager(accessDecisionManager());
    fsi.setAuthenticationManager(authenticationManagerBean());
    return fsi;
    }
    }).and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login.html")).and().logout().logoutSuccessUrl("/index.html").permitAll();
    // 自定义accessDecisionManager访问控制器,并开启表达式语言
    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler()).and().authorizeRequests().anyRequest().authenticated().expressionHandler(webSecurityExpressionHandler()); // 自定义登录页面
    http.csrf().disable(); // 自定义注销
    // http.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
    // .invalidateHttpSession(true); // session管理
    http.sessionManagement().maximumSessions(1); // RemeberMe
    // http.rememberMe().key("webmvc#FD637E6D9C0F1A5A67082AF56CE32485");

    }

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    // 自定义UserDetailsService

    auth.userDetailsService(userDetailsService);

    }

    @Bean

    UsernamePasswordAuthenticationFilter MyUsernamePasswordAuthenticationFilter() {

    UsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter = new UsernamePasswordAuthenticationFilter();

    myUsernamePasswordAuthenticationFilter.setPostOnly(true);

    myUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());

    myUsernamePasswordAuthenticationFilter.setUsernameParameter("name_key");

    myUsernamePasswordAuthenticationFilter.setPasswordParameter("pwd_key");

    myUsernamePasswordAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));

    myUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(simpleUrlAuthenticationFailureHandler());

    return myUsernamePasswordAuthenticationFilter;

    }

    @Bean

    AccessDeniedHandler accessDeniedHandler() {

    AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl();

    accessDeniedHandler.setErrorPage("/securityException/accessDenied");

    return accessDeniedHandler;

    }

    @Bean

    public LoggerListener loggerListener() {

    System.out.println("org.springframework.security.authentication.event.LoggerListener");

    return new LoggerListener();

    }

    @Bean

    public org.springframework.security.access.event.LoggerListener eventLoggerListener() {

    System.out.println("org.springframework.security.access.event.LoggerListener");

    return new org.springframework.security.access.event.LoggerListener();

    }

    /*

    • 这里可以增加自定义的投票器

      */

      @Bean(name = "accessDecisionManager")

      public AccessDecisionManager accessDecisionManager() {

      List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList();

      decisionVoters.add(new RoleVoter());

      decisionVoters.add(new AuthenticatedVoter());

      decisionVoters.add(webExpressionVoter());// 启用表达式投票器

      MyAccessDecisionManager accessDecisionManager = new MyAccessDecisionManager(decisionVoters);

      return accessDecisionManager;

      }

    @Bean(name = "authenticationManager")

    @Override

    public AuthenticationManager authenticationManagerBean() {

    AuthenticationManager authenticationManager = null;

    try {

    authenticationManager = super.authenticationManagerBean();

    } catch (Exception e) {

    e.printStackTrace();

    }

    return authenticationManager;

    }

    @Bean(name = "failureHandler")

    public SimpleUrlAuthenticationFailureHandler simpleUrlAuthenticationFailureHandler() {

    return new SimpleUrlAuthenticationFailureHandler("/getLoginError");

    }

    @Bean(name = "aclResourcesService")

    @ConditionalOnMissingBean

    public AclResourcesService aclResourcesService() {

    return new AclResourcesServiceImpl();

    }

    /*

    • 表达式控制器

      */

      @Bean(name = "expressionHandler")

      public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {

      DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();

      return webSecurityExpressionHandler;

      }

    /*

    • 表达式投票器

      */

      @Bean(name = "expressionVoter")

      public WebExpressionVoter webExpressionVoter() {

      WebExpressionVoter webExpressionVoter = new WebExpressionVoter();

      webExpressionVoter.setExpressionHandler(webSecurityExpressionHandler());

      return webExpressionVoter;

      }

}

自定义 UserDetailsService 用户、角色、资源获取类:

src/main/java/com/training/core/security/UserDetailsServiceImpl.java

  1. package com.training.core.security;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import org.springframework.security.core.GrantedAuthority;
  6. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  7. import org.springframework.security.core.userdetails.User;
  8. import org.springframework.security.core.userdetails.UserDetails;
  9. import org.springframework.security.core.userdetails.UserDetailsService;
  10. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  11. import org.springframework.stereotype.Service;
  12. import com.training.sysmanager.entity.AclResources;
  13. import com.training.sysmanager.entity.AclUser;
  14. import com.training.sysmanager.service.AclResourcesService;
  15. import com.training.sysmanager.service.AclRoleResourcesService;
  16. import com.training.sysmanager.service.AclUserService;
  17. /**
  18. * Created by Athos on 2016-10-16.
  19. */
  20. @Service("userDetailsService")
  21. public class UserDetailsServiceImpl  implements UserDetailsService {
  22. @Resource
  23. private AclUserService aclUserService;
  24. @Resource
  25. private AclRoleResourcesService aclRoleResourcesService;
  26. @Resource
  27. private AclResourcesService aclResourcesService;
  28. /* (non-Javadoc)
  29. * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
  30. */
  31. @Override
  32. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  33. List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
  34. AclUser aclUser = aclUserService.findAclUserByName(username);
  35. String resourceIds = aclRoleResourcesService.selectResourceIdsByRoleIds(aclUser.getRoleIds());
  36. List<AclResources> aclResourcesList = aclResourcesService.selectAclResourcesByResourceIds(resourceIds);
  37. for (AclResources aclResources : aclResourcesList) {
  38. auths.add(new SimpleGrantedAuthority(aclResources.getAuthority().toUpperCase()));
  39. }
  40. //        auths.addAll(aclResourcesList.stream().map(resources -> new SimpleGrantedAuthority(resources.getAuthority().toUpperCase())).collect(Collectors.toList()));
  41. return new User(aclUser.getUserName().toLowerCase(),aclUser.getUserPwd().toLowerCase(),true,true,true,true,auths);
  42. }
  43. }
package com.training.core.security;

import java.util.ArrayList;

import java.util.List; import javax.annotation.Resource; import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.User;

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.Service; import com.training.sysmanager.entity.AclResources;

import com.training.sysmanager.entity.AclUser;

import com.training.sysmanager.service.AclResourcesService;

import com.training.sysmanager.service.AclRoleResourcesService;

import com.training.sysmanager.service.AclUserService; /**
  • Created by Athos on 2016-10-16.

    */

    @Service("userDetailsService")

    public class UserDetailsServiceImpl implements UserDetailsService { @Resource

    private AclUserService aclUserService;

    @Resource

    private AclRoleResourcesService aclRoleResourcesService;

    @Resource

    private AclResourcesService aclResourcesService; /* (non-Javadoc)
    • @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)

      */

      @Override

      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

      List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();

      AclUser aclUser = aclUserService.findAclUserByName(username);

      String resourceIds = aclRoleResourcesService.selectResourceIdsByRoleIds(aclUser.getRoleIds());

      List<AclResources> aclResourcesList = aclResourcesService.selectAclResourcesByResourceIds(resourceIds);

      for (AclResources aclResources : aclResourcesList) {

      auths.add(new SimpleGrantedAuthority(aclResources.getAuthority().toUpperCase()));

      }

      // auths.addAll(aclResourcesList.stream().map(resources -> new SimpleGrantedAuthority(resources.getAuthority().toUpperCase())).collect(Collectors.toList()));

      return new User(aclUser.getUserName().toLowerCase(),aclUser.getUserPwd().toLowerCase(),true,true,true,true,auths);

      }

      }

自定义securityMetadataSource:

src/main/java/com/training/core/security/MySecurityMetadataSource.java

  1. package com.training.core.security;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import javax.servlet.http.HttpServletRequest;
  9. import org.springframework.security.access.ConfigAttribute;
  10. import org.springframework.security.access.SecurityConfig;
  11. import org.springframework.security.web.FilterInvocation;
  12. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  13. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  14. import org.springframework.security.web.util.matcher.RequestMatcher;
  15. import org.springframework.stereotype.Component;
  16. import com.training.sysmanager.entity.AclResources;
  17. import com.training.sysmanager.service.AclResourcesService;
  18. /**
  19. * Created by Athos on 2016-10-16.
  20. */
  21. @Component("mySecurityMetadataSource")
  22. public class MySecurityMetadataSource  implements FilterInvocationSecurityMetadataSource {
  23. private static Map<String,Collection<ConfigAttribute>> aclResourceMap = null;
  24. private AclResourcesService aclResourcesService;
  25. /**
  26. * 构造方法
  27. */
  28. //1
  29. public MySecurityMetadataSource(AclResourcesService aclResourcesService){
  30. this.aclResourcesService=aclResourcesService;
  31. loadResourceDefine();
  32. }
  33. @Override
  34. public Collection<ConfigAttribute> getAttributes(Object object)throws IllegalArgumentException{
  35. HttpServletRequest request=((FilterInvocation)object).getRequest();
  36. Iterator<String> ite = aclResourceMap.keySet().iterator();
  37. while (ite.hasNext()){
  38. String resURL = ite.next();
  39. RequestMatcher requestMatcher = new AntPathRequestMatcher(resURL);
  40. if(requestMatcher.matches(request)){
  41. return aclResourceMap.get(resURL);
  42. }
  43. }
  44. return null;
  45. }
  46. //4
  47. @Override
  48. public Collection<ConfigAttribute> getAllConfigAttributes() {
  49. System.out.println("metadata : getAllConfigAttributes");
  50. return null;
  51. }
  52. //3
  53. @Override
  54. public boolean supports(Class<?> clazz) {
  55. System.out.println("metadata : supports");
  56. return true;
  57. }
  58. private void loadResourceDefine(){
  59. /**
  60. * 因为只有权限控制的资源才需要被拦截验证,所以只加载有权限控制的资源
  61. */
  62. List<AclResources> aclResourceses = aclResourcesService.selectAclResourcesTypeOfRequest();
  63. aclResourceMap = new HashMap<>();
  64. for (AclResources aclResources:aclResourceses){
  65. ConfigAttribute ca = new SecurityConfig(aclResources.getAuthority().toUpperCase());
  66. String url = aclResources.getUrl();
  67. if(aclResourceMap.containsKey(url)){
  68. Collection<ConfigAttribute> value = aclResourceMap.get(url);
  69. value.add(ca);
  70. aclResourceMap.put(url,value);
  71. }else {
  72. Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
  73. atts.add(ca);
  74. aclResourceMap.put(url,atts);
  75. }
  76. }
  77. }
  78. }
package com.training.core.security;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map; 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.security.web.util.matcher.AntPathRequestMatcher;

import org.springframework.security.web.util.matcher.RequestMatcher;

import org.springframework.stereotype.Component; import com.training.sysmanager.entity.AclResources;

import com.training.sysmanager.service.AclResourcesService; /**
  • Created by Athos on 2016-10-16.

    */

    @Component("mySecurityMetadataSource")

    public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource { private static Map<String,Collection<ConfigAttribute>> aclResourceMap = null;

    private AclResourcesService aclResourcesService; /**
    • 构造方法

      */

      //1

      public MySecurityMetadataSource(AclResourcesService aclResourcesService){

      this.aclResourcesService=aclResourcesService;

      loadResourceDefine();

      }
    @Override

    public Collection<ConfigAttribute> getAttributes(Object object)throws IllegalArgumentException{

    HttpServletRequest request=((FilterInvocation)object).getRequest();

    Iterator<String> ite = aclResourceMap.keySet().iterator();

    while (ite.hasNext()){

    String resURL = ite.next();

    RequestMatcher requestMatcher = new AntPathRequestMatcher(resURL);

    if(requestMatcher.matches(request)){

    return aclResourceMap.get(resURL);

    }

    }

    return null;

    }

    //4

    @Override

    public Collection<ConfigAttribute> getAllConfigAttributes() {

    System.out.println("metadata : getAllConfigAttributes");

    return null;

    }

    //3

    @Override

    public boolean supports(Class<?> clazz) {

    System.out.println("metadata : supports");

    return true;

    } private void loadResourceDefine(){

    /**

    * 因为只有权限控制的资源才需要被拦截验证,所以只加载有权限控制的资源

    */

    List<AclResources> aclResourceses = aclResourcesService.selectAclResourcesTypeOfRequest();

    aclResourceMap = new HashMap<>();

    for (AclResources aclResources:aclResourceses){

    ConfigAttribute ca = new SecurityConfig(aclResources.getAuthority().toUpperCase());

    String url = aclResources.getUrl();

    if(aclResourceMap.containsKey(url)){

    Collection<ConfigAttribute> value = aclResourceMap.get(url);

    value.add(ca);

    aclResourceMap.put(url,value);
         }else {
    Collection&lt;ConfigAttribute&gt; atts = new ArrayList&lt;ConfigAttribute&gt;();
    atts.add(ca);
    aclResourceMap.put(url,atts);
    }
    }

    }

    }

自定义AbstractAccessDecisionManager权限决策类,

src/main/java/com/training/core/security/MyAccessDecisionManager.java

  1. package com.training.core.security;
  2. import org.springframework.security.access.AccessDecisionVoter;
  3. import org.springframework.security.access.AccessDeniedException;
  4. import org.springframework.security.access.ConfigAttribute;
  5. import org.springframework.security.access.vote.AbstractAccessDecisionManager;
  6. import org.springframework.security.authentication.InsufficientAuthenticationException;
  7. import org.springframework.security.core.Authentication;
  8. import org.springframework.security.core.GrantedAuthority;
  9. import java.util.Collection;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. /**
  13. * Created by Athos on 2016-10-16.
  14. */
  15. public class MyAccessDecisionManager  extends AbstractAccessDecisionManager {
  16. protected MyAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
  17. super(decisionVoters);
  18. }
  19. @Override
  20. public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
  21. if(configAttributes==null){
  22. return;
  23. }
  24. Iterator<ConfigAttribute> ite = configAttributes.iterator();
  25. while(ite.hasNext()){
  26. ConfigAttribute ca = ite.next();
  27. String needRole = (ca).getAttribute();
  28. for (GrantedAuthority ga : authentication.getAuthorities()){
  29. if (needRole.equals(ga.getAuthority())){
  30. return;
  31. }
  32. }
  33. }
  34. throw new AccessDeniedException("没有权限,拒绝访问!");
  35. }
  36. @Override
  37. public boolean supports(ConfigAttribute attribute) {
  38. return false;
  39. }
  40. /**
  41. * Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support
  42. * the presented class.
  43. * <p>
  44. * If one or more voters cannot support the presented class, <code>false</code> is
  45. * returned.
  46. *
  47. * @param clazz the type of secured object being presented
  48. * @return true if this type is supported
  49. */
  50. @Override
  51. public boolean supports(Class<?> clazz) {
  52. return true;
  53. }
  54. }
package com.training.core.security;

import org.springframework.security.access.AccessDecisionVoter;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.access.vote.AbstractAccessDecisionManager;

import org.springframework.security.authentication.InsufficientAuthenticationException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.GrantedAuthority; import java.util.Collection;

import java.util.Iterator;

import java.util.List; /**
  • Created by Athos on 2016-10-16.

    */
public class MyAccessDecisionManager extends AbstractAccessDecisionManager {

protected MyAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {

super(decisionVoters);

}
@Override
public void decide(Authentication authentication, Object object, Collection&lt;ConfigAttribute&gt; configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes==null){
return;
}
Iterator&lt;ConfigAttribute&gt; ite = configAttributes.iterator();
while(ite.hasNext()){
ConfigAttribute ca = ite.next();
String needRole = (ca).getAttribute();
for (GrantedAuthority ga : authentication.getAuthorities()){
if (needRole.equals(ga.getAuthority())){
return;
}
}
}
throw new AccessDeniedException("没有权限,拒绝访问!");
}
@Override
public boolean supports(ConfigAttribute attribute) {
return false;
} /**
* Iterates through all &lt;code&gt;AccessDecisionVoter&lt;/code&gt;s and ensures each can support
* the presented class.
* &lt;p&gt;
* If one or more voters cannot support the presented class, &lt;code&gt;false&lt;/code&gt; is
* returned.
*
* @param clazz the type of secured object being presented
* @return true if this type is supported
*/
@Override
public boolean supports(Class&lt;?&gt; clazz) {
return true;
}

}

用户、角色、资源(菜单)略。

详情请看GIT完成工程。

https://github.com/FrameReserve/TrainingBoot

        </div>

Spring Boot 集成spring security4的更多相关文章

  1. Spring Boot集成Spring Data Reids和Spring Session实现Session共享

    首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...

  2. SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache

    前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...

  3. SpringBoot系列:Spring Boot集成Spring Cache,使用RedisCache

    前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...

  4. Spring Boot 集成 Spring Security 实现权限认证模块

    作者:王帅@CodeSheep   写在前面 关于 Spring Security Web系统的认证和权限模块也算是一个系统的基础设施了,几乎任何的互联网服务都会涉及到这方面的要求.在Java EE领 ...

  5. Spring boot集成spring session实现session共享

    最近使用spring boot开发一个系统,nginx做负载均衡分发请求到多个tomcat,此时访问页面会把请求分发到不同的服务器,session是存在服务器端,如果首次访问被分发到A服务器,那么se ...

  6. Spring boot 集成Spring Security

    依赖jar <dependency> <groupId>org.springframework.cloud</groupId> <artifactId> ...

  7. SpringBoot系列:Spring Boot集成Spring Cache

    一.关于Spring Cache 缓存在现在的应用中越来越重要, Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework. ...

  8. Spring Boot 集成 Spring Security

    1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  9. Spring Boot 集成 Spring Security 入门案例教程

    前言 本文作为入门级的DEMO,完全按照官网实例演示: 项目目录结构 Maven 依赖 <parent> <groupId>org.springframework.boot&l ...

随机推荐

  1. UVA 1661 Equation (后缀表达式,表达式树,模拟,实现)

    题意:给出一个后缀表达式f(x),最多出现一次x,解方程f(x) = 0. 读取的时候用一个栈保存之前的结点,可以得到一颗二叉树,标记出现'X'的路径,先把没有出现'X'的子树算完,由于读取建树的时候 ...

  2. java 中设计模式

    1. 单例模式(一个类只有一个实例) package ch.test.notes.designmodel; /** * Description: 单例模式 (饿汉模式 线程安全的) * * @auth ...

  3. selenium+chrome浏览器驱动-爬取百度图片

    百度图片网页中中,当页面滚动到底部,页面会加载新的内容. 我们通过selenium和谷歌浏览器驱动,执行js,是浏览器不断加载页面,通过抓取页面的图片路径来下载图片. from selenium im ...

  4. WPF知识点全攻略07- 数据绑定(Binding)

    数据绑定是WPF不得不提,不得不会系列之一 数据绑定简言之,就是把数据源的数据绑定到目标对象的属性上.目标对象可以是承自DependencyProperty的任何可访问的属性或控件,目标属性必须为依赖 ...

  5. 怎么在webstorm中设置代码模板

    大家都知道webstorm对程序员来说是一个很好用的IDE.我们输入几个关键字,webstorm就会给出提示,大大提高了我们的开发效率,可有时候webstorm的默认设置不能满足我们的个性化代码模板的 ...

  6. c++ 各种类型字符串转换

    typedef std::string u8string; u8string To_UTF8(const std::u16string &s) { std::wstring_convert&l ...

  7. 剑指offer44 扑克牌顺序

    注意一个边界条件:必须是连续的,如果前后两个数是一样的也不满足条件 class Solution { public: bool IsContinuous( vector<int> numb ...

  8. Dev-Cpp 5.11 c++编译器下载

    Dev-Cpp 5.11 c++编译器下载地址: 链接: https://pan.baidu.com/s/1jHMAf1k 密码: i6nw

  9. Web字节码(WebAssembly) Emscripten编译器安装

    首先你需要提前安装 git python 环境并且Ctrl+R输入cmd在windows的dos界面下能够运行 第一步: 在github上downloade下来emsdk git clone http ...

  10. js中小数精度问题

    js中小数的取值为近似值,可能比实际值大,也可能比实际值小,进行“四舍五入”得到的 例如:alert(0.1+0.2);值为0.300000004     alert(0.2+0.7);值为1.899 ...