Spring Boot 集成spring security4
项目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项目地址
- <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>
- <spring-security.version>4.1.0.RELEASE</spring-security.version>
- </properties>
- <!-- 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>
<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><spring-security.version>4.1.0.RELEASE</spring-security.version>
</properties>
<!-- 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
- 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<FilterSecurityInterceptor>() {
- public <O extends FilterSecurityInterceptor> 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;
- }
- }
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<FilterSecurityInterceptor>() {
public <O extends FilterSecurityInterceptor> 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
- 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);
- }
- }
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);
}
}
- @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
自定义securityMetadataSource:
src/main/java/com/training/core/security/MySecurityMetadataSource.java
- 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<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
- atts.add(ca);
- aclResourceMap.put(url,atts);
- }
- }
- }
- }
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();
}
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<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
atts.add(ca);
aclResourceMap.put(url,atts);
}
}
}
}
- 构造方法
自定义AbstractAccessDecisionManager权限决策类,
src/main/java/com/training/core/security/MyAccessDecisionManager.java
- 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<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
- if(configAttributes==null){
- return;
- }
- Iterator<ConfigAttribute> 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 <code>AccessDecisionVoter</code>s and ensures each can support
- * the presented class.
- * <p>
- * If one or more voters cannot support the presented class, <code>false</code> is
- * returned.
- *
- * @param clazz the type of secured object being presented
- * @return true if this type is supported
- */
- @Override
- public boolean supports(Class<?> clazz) {
- return true;
- }
- }
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.
*/
protected MyAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes==null){
return;
}
Iterator<ConfigAttribute> 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 <code>AccessDecisionVoter</code>s and ensures each can support
* the presented class.
* <p>
* If one or more voters cannot support the presented class, <code>false</code> is
* returned.
*
* @param clazz the type of secured object being presented
* @return true if this type is supported
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
用户、角色、资源(菜单)略。
详情请看GIT完成工程。
https://github.com/FrameReserve/TrainingBoot
</div>
Spring Boot 集成spring security4的更多相关文章
- Spring Boot集成Spring Data Reids和Spring Session实现Session共享
首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...
- SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache
前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...
- SpringBoot系列:Spring Boot集成Spring Cache,使用RedisCache
前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...
- Spring Boot 集成 Spring Security 实现权限认证模块
作者:王帅@CodeSheep 写在前面 关于 Spring Security Web系统的认证和权限模块也算是一个系统的基础设施了,几乎任何的互联网服务都会涉及到这方面的要求.在Java EE领 ...
- Spring boot集成spring session实现session共享
最近使用spring boot开发一个系统,nginx做负载均衡分发请求到多个tomcat,此时访问页面会把请求分发到不同的服务器,session是存在服务器端,如果首次访问被分发到A服务器,那么se ...
- Spring boot 集成Spring Security
依赖jar <dependency> <groupId>org.springframework.cloud</groupId> <artifactId> ...
- SpringBoot系列:Spring Boot集成Spring Cache
一.关于Spring Cache 缓存在现在的应用中越来越重要, Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework. ...
- Spring Boot 集成 Spring Security
1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- Spring Boot 集成 Spring Security 入门案例教程
前言 本文作为入门级的DEMO,完全按照官网实例演示: 项目目录结构 Maven 依赖 <parent> <groupId>org.springframework.boot&l ...
随机推荐
- UVA 1661 Equation (后缀表达式,表达式树,模拟,实现)
题意:给出一个后缀表达式f(x),最多出现一次x,解方程f(x) = 0. 读取的时候用一个栈保存之前的结点,可以得到一颗二叉树,标记出现'X'的路径,先把没有出现'X'的子树算完,由于读取建树的时候 ...
- java 中设计模式
1. 单例模式(一个类只有一个实例) package ch.test.notes.designmodel; /** * Description: 单例模式 (饿汉模式 线程安全的) * * @auth ...
- selenium+chrome浏览器驱动-爬取百度图片
百度图片网页中中,当页面滚动到底部,页面会加载新的内容. 我们通过selenium和谷歌浏览器驱动,执行js,是浏览器不断加载页面,通过抓取页面的图片路径来下载图片. from selenium im ...
- WPF知识点全攻略07- 数据绑定(Binding)
数据绑定是WPF不得不提,不得不会系列之一 数据绑定简言之,就是把数据源的数据绑定到目标对象的属性上.目标对象可以是承自DependencyProperty的任何可访问的属性或控件,目标属性必须为依赖 ...
- 怎么在webstorm中设置代码模板
大家都知道webstorm对程序员来说是一个很好用的IDE.我们输入几个关键字,webstorm就会给出提示,大大提高了我们的开发效率,可有时候webstorm的默认设置不能满足我们的个性化代码模板的 ...
- c++ 各种类型字符串转换
typedef std::string u8string; u8string To_UTF8(const std::u16string &s) { std::wstring_convert&l ...
- 剑指offer44 扑克牌顺序
注意一个边界条件:必须是连续的,如果前后两个数是一样的也不满足条件 class Solution { public: bool IsContinuous( vector<int> numb ...
- Dev-Cpp 5.11 c++编译器下载
Dev-Cpp 5.11 c++编译器下载地址: 链接: https://pan.baidu.com/s/1jHMAf1k 密码: i6nw
- Web字节码(WebAssembly) Emscripten编译器安装
首先你需要提前安装 git python 环境并且Ctrl+R输入cmd在windows的dos界面下能够运行 第一步: 在github上downloade下来emsdk git clone http ...
- js中小数精度问题
js中小数的取值为近似值,可能比实际值大,也可能比实际值小,进行“四舍五入”得到的 例如:alert(0.1+0.2);值为0.300000004 alert(0.2+0.7);值为1.899 ...