,## springboot框架配置
springboot项目搭建大家可以去请教度娘,有很多文章,这里主要讲解springboot和security安全框架的集成,因为springmvc跟security集成中,大部分都是采用配置文件的形式,本例中完全没用配置文件,配置文件的方式写起来比较省事,但是比较难懂,导致我在写这个的时候网上搜的资料也不多,很难搞,好不容易弄好了,怕自己忘记,特此记录一下。
表格部分:分为五个表格
sys_user
sys_role
sys_menu
sys_user_role
sys_role_menu
分表创建实体Bean,数据访问层是用的hibernate,具体代码可参见附件
安全框架配置部分
配置文件那种的方式最主要的是配置文件,而不用配置文件最主要的就是自定义的去实现WebSecurityConfigurerAdapter类,大体的思路为:
1、WebSecurityConfig===》WebSecurityConfigurerAdapter(主要配置文件)
2、MyAuthenticationProvider==》AuthenticationProvider(自定义验证用户名密码)
3、CustomUserDetailsService==》UserDetailsService(MyAuthenticationProvider需要调用)
4、mySecurityFilter==》AbstractSecurityInterceptor 、Filter(自定义的过滤器)
5、FilterSourceMetadataSource==》FilterInvocationSecurityMetadataSource(过滤器调用,过滤器加载资源)
6、MyAccessDecisionManager ==》AccessDecisionManager(过滤器调用,验证用户是否有权限访问资源)
下面是WebSecurityConfig
package com.zy.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.stereotype.Service;
/**
* @Author zhang
* @create 2017-07-14-15:51
* @desc ${DESCRIPTION}
**/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationProvider authenticationProvider;
@Autowired
private MySecurityFilter mySecurityFilter;
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//允许所有用户访问"/"和"/home"
http
.addFilterBefore(mySecurityFilter, FilterSecurityInterceptor.class)//在正确的位置添加我们自定义的过滤器
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home","403").permitAll()//访问:/home 无需登录认证权限
//其他地址的访问均需验证权限
.anyRequest().authenticated()//其他所有资源都需要认证,登陆后访问
.and()
.formLogin()
//指定登录页是"/login"
.loginPage("/login")
.defaultSuccessUrl("/index")//登录成功后默认跳转到"/hello"
// .failureUrl("/403")
.permitAll()
//.successHandler(loginSuccessHandler())//code3
.and()
.logout()
.logoutSuccessUrl("/")//退出登录后的默认url是"/home"
.permitAll()
.and()
.rememberMe()//登录后记住用户,下次自动登录,数据库中必须存在名为persistent_logins的表
.tokenValiditySeconds(1209600); ;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
auth.userDetailsService(customUserDetailsService()).passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
//可以仿照上面一句忽略静态资源
}
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth.authenticationProvider(authenticationProvider);
// }
/**
* 设置用户密码的加密方式为MD5加密
* @return
*/
@Bean
public Md5PasswordEncoder passwordEncoder() {
return new Md5PasswordEncoder();
}
/**
* 自定义UserDetailsService,从数据库中读取用户信息
* @return
*/
@Bean
public CustomUserDetailsService customUserDetailsService(){
return new CustomUserDetailsService();
}
//
}
类MyAuthenticationProvider 自定义的用户名密码验证,调用了loadUserByUsername方法
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException{
String username = authentication.getName();
String password = (String) authentication.getCredentials();
UserDetails user = customUserDetailsService.loadUserByUsername(username);
if(user == null){
throw new BadCredentialsException("用户没有找到");
}
//加密过程在这里体现
if (!password.equals(user.getPassword())) {
System.out.print("密码错误");
throw new BadCredentialsException("密码错误");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
public boolean supports(Class<?> var1){
return true;
}
}
类CustomUserDetailsService 实现 UserDetailsService
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private ActionRepository actionRepository;
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{
try {
UserBean user = userService.findUserByName(userName);
if(null == user){
throw new UsernameNotFoundException("UserName " + userName + " not found");
}
// SecurityUser实现UserDetails并将SUser的Email映射为username
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (RoleBean ur : user.getRoleBeans()) {
String name = ur.getRoleName();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(name);
authorities.add(grantedAuthority);
}
return new User(
user.getUsername(),
user.getPassword(),
authorities);
}catch ( Exception e){
e.printStackTrace();
return null;
}
}
}
类MySecurityFilter 自定义过滤器,拦截器我本来没有自定义,但是会有问题一些访问的资源什么的没有办法过滤掉。
package com.zy.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.servlet.*;
import java.io.IOException;
/**
* @Author toplion
* @create 2017-08-03-17:00
* @desc ${DESCRIPTION}
**/
@Service
public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter{
@Autowired
private FilterSourceMetadataSource filterInvocationSource;
@Autowired
private MyAccessDecisionManager myAccessDecisionManager;
@Autowired
private AuthenticationManager authenticationManager;
@PostConstruct
public void init(){
super.setAuthenticationManager(authenticationManager);
super.setAccessDecisionManager(myAccessDecisionManager);
}
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
FilterInvocation fi = new FilterInvocation( request, response, chain );
invoke(fi);
}
public Class<? extends Object> getSecureObjectClass(){
return FilterInvocation.class;
}
public void invoke( FilterInvocation fi ) throws IOException, ServletException{
System.out.println("filter..........................");
InterceptorStatusToken token = super.beforeInvocation(fi);
try{
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
}finally{
super.afterInvocation(token, null);
}
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource(){
System.out.println("filtergergetghrthetyetyetyetyj");
return this.filterInvocationSource;
}
public void destroy(){
System.out.println("filter===========================end");
}
public void init( FilterConfig filterconfig ) throws ServletException{
System.out.println("filter===========================");
}
}
类FilterSourceMetadataSource
@Service
public class FilterSourceMetadataSource implements FilterInvocationSecurityMetadataSource {
private static Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
private ActionRepository menuService;
private RequestMatcher pathMatcher;
@Autowired
public FilterSourceMetadataSource(ActionRepository repository) {
this.menuService = repository;
loadResourcePermission();
}
/**
* 返回所请求资源所需要的权限
* 针对资源的URL
* @param o
* @return
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
Iterator<String> resourceUrls = resourceMap.keySet().iterator();
while (resourceUrls.hasNext()) {
String resUrl = resourceUrls.next();
System.out.print("**********************************"+resUrl);
if(null == resUrl || resUrl.isEmpty()) {
continue;
}
pathMatcher = new AntPathRequestMatcher(resUrl);
if (pathMatcher.matches(((FilterInvocation) o).getRequest())) {
Collection<ConfigAttribute> configAttributes = resourceMap.get(resUrl);
return configAttributes;
}
}
return null;
}
/**
* 获取所有配置权限
* @return
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Collection<Collection<ConfigAttribute>> cacs = resourceMap.values();
Collection<ConfigAttribute> cac = new HashSet<ConfigAttribute>();
for (Collection<ConfigAttribute> c: cacs) {
cac.addAll(c);
}
return cac;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
/**
* 加载资源的权限
*/
private void loadResourcePermission() {
loadMenuPermisson();
}
/**
* 加载菜单的权限
*/
private void loadMenuPermisson() {
List<ActionBean> menus = menuService.findAll();
for (ActionBean menu: menus) {
List<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
// MenuEntity currMenu = menuService.getMenuById(menu.getMenuId());
Hibernate.initialize(menu);
ConfigAttribute configAttribute = new SecurityConfig(menu.getMenuCode());
configAttributes.add(configAttribute);
if(null != resourceMap.get(menu.getMenuUrl())) {
resourceMap.get(menu.getMenuUrl()).addAll(configAttributes);
} else {
resourceMap.put(menu.getMenuUrl(), configAttributes);
}
}
System.out.println(resourceMap);
}
}
类MyAccessDecisionManager
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {
/**
* 验证用户是否有权限访问资源
* @param authentication
* @param o
* @param configAttributes
* @throws AccessDeniedException
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
/*允许访问没有设置权限的资源*/
if(configAttributes == null) {
return;
}
/*一个资源可以由多个权限访问,用户拥有其中一个权限即可访问该资源*/
Iterator<ConfigAttribute> configIterator = configAttributes.iterator();
while (configIterator.hasNext()) {
ConfigAttribute configAttribute = configIterator.next();
String needPermission = configAttribute.getAttribute();
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needPermission.equals(ga.getAuthority())) {
return;
}
}
}
throw new AccessDeniedException("没有权限访问");
}
/**
* 特定configAttribute的支持
* @param configAttribute
* @return
*/
@Override
public boolean supports(ConfigAttribute configAttribute) {
/*支持所有configAttribute*/
return true;
}
/**
* 特定安全对象类型支持
* @param aClass
* @return
*/
@Override
public boolean supports(Class<?> aClass) {
/*支持所有对象类型*/
return true;
}
}