【Spring实战】----spring security4.1.3配置以及踩过的坑

spring security完全可以作为一个专门的专题来说,有一个专题写的不错http://www.iteye.com/blogs/subjects/spring_security,我这里主要是针对4.1.3进行配置说明


一、所需的库文件

//spring-security
	compile 'org.springframework.security:spring-security-web:4.1.3.RELEASE'
	compile 'org.springframework.security:spring-security-config:4.1.3.RELEASE'
	compile 'org.springframework.security:spring-security-taglibs:4.1.3.RELEASE'


二、web配置

从4以后security就只吃java配置了,具体可以看下《spring in action第四版》,我这里还是使用xml配置

过滤器配置,security是基于过滤器的,web.xml


	
		springSecurityFilterChain
		
			org.springframework.web.filter.DelegatingFilterProxy
		
	
	
		springSecurityFilterChain
		/*
	

需要注意的是,如果配置了sitemesh装饰器,如果在装饰器页面中用到了security,比如标签,那么security过滤器需要配置在sitemesh之前,否则装饰器页中的标签可能不起作用


	
		springSecurityFilterChain
		
			org.springframework.web.filter.DelegatingFilterProxy
		
	
	
		springSecurityFilterChain
		/*
	
	
	
	
		sitemesh
		
			org.sitemesh.config.ConfigurableSiteMeshFilter
		
			
			ignore
			true
		
		
			encoding
			UTF-8
		
	
	
		sitemesh
		/*
	

装饰器页面中的使用


        			
  • 你好,欢迎来到Mango!登录
  • 欢迎光临Mango!退出

  • 三、security配置文件配置

    applicationContext-security.xml

    
    
    
    		
    	
    		   
             
             
             
    		
    		
    		
    	
    	
    	
    	  
              
            	
                
                
            
        
    	
    

    这里配置了自定义登录界面/login,还需要配置控制器条撞到login.jsp页面,如果字段使用默认值为username和password,当然也可以用 form-login标签中的属性username-parameter="username"password-parameter="password" 进行设置,这里的值要和登录页面中的字段一致。login.jsp

    <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
    <%@ include file="../includes/taglibs.jsp"%>
    
    
    
        Mango-Login
    	    
    
    
    
    
    

    请登录!

    ${error}

    用户名:
    密码:

    其中,form action的值要和配置文件中login-process-url的值一致,提交后UsernamePasswordAuthenticationFilter才能对其进行授权认证。
    另外认证是采用的自定义myUserDetailsService获取用户信息方式,由于该项目中集成的是Hibernate,所以自己定义了,security系统中是支持jdbc进行获取的

    package com.mango.jtt.springSecurity;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.authority.AuthorityUtils;
    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.mango.jtt.po.MangoUser;
    import com.mango.jtt.service.IUserService;
    
    /**
     * 从数据库中获取信息的自定义类
     * 
     * @author HHL
     * 
     */
    @Service
    public class MyUserDetailsService implements UserDetailsService {
    	
    	@Autowired
    	private IUserService userService;
    
    	/**
    	 * 获取用户信息,设置角色
    	 */
    	@Override
    	public UserDetails loadUserByUsername(String username)
    			throws UsernameNotFoundException {
    		// 获取用户信息
    		MangoUser mangoUser = userService.getUserByName(username);
    		if (mangoUser != null) {
    			// 设置角色
    			return new User(mangoUser.getUserName(), mangoUser.getPassword(),
    					AuthorityUtils.createAuthorityList(mangoUser.getRole()));
    		}
    
    		throw new UsernameNotFoundException("User '" + username
    					+ "' not found.");
    	}
    	
    }
    


    认证成功之后也是自定义了处理类myAuthenticationSuccessHandler,该处理类继承了SavedRequestAwareAuthenticationSuccessHandler,实现了保存请求信息的操作,如果不配置,默认的也是交给SavedRequestAwareAuthenticationSuccessHandler处理,因为在解析security配置文件时,如果没有配置会将此设置为默认值。

    package com.mango.jtt.springSecurity;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
    import org.springframework.stereotype.Component;
    
    import com.mango.jtt.po.MangoUser;
    import com.mango.jtt.service.IUserService;
    
    /**
     * 登录后操作
     * 
     * @author HHL
     * @date
     * 
     */
    @Component
    public class MyAuthenticationSuccessHandler extends
    		SavedRequestAwareAuthenticationSuccessHandler {
    
    	@Autowired
    	private IUserService userService;
    
    	@Override
    	public void onAuthenticationSuccess(HttpServletRequest request,
    			HttpServletResponse response, Authentication authentication)
    			throws IOException, ServletException {
    
    		// 认证成功后,获取用户信息并添加到session中
    		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    		MangoUser user = userService.getUserByName(userDetails.getUsername());
    		request.getSession().setAttribute("user", user);
    		
    		super.onAuthenticationSuccess(request, response, authentication);
    	
    	}
    
    
    }
    


    认证失败则回到登录页,只不过多了error,配置为authentication-failure-url="/login?error" 控制类会对其进行处理

    /**
     * 
     */
    package com.mango.jtt.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    /**
     * @author HHL
     * 
     * @date 2016年12月8日
     * 
     *       用户控制类
     */
    @Controller
    public class UserController {
    	
    	/**
    	 * 显示登录页面用,主要是显示错误信息
    	 * 
    	 * @param model
    	 * @param error
    	 * @return
    	 */
    	@RequestMapping("/login")
    	public String login(Model model,
    			@RequestParam(value = "error", required = false) String error) {
    		if (error != null) {
    			model.addAttribute("error", "用户名或密码错误");
    		}
    		return "login";
    	}
    }
    

    另外,从spring security3.2开始,默认就会启用csrf保护,本次将csrf保护功能禁用,防止页面中没有配置crsf而报错“Could not verify the provided CSRF token because your session was not found.”,如果启用csrf功能的话需要将login和logout以及上传功能等都需要进行相应的设置,因此这里先禁用csrf保护功能具体可参考spring-security4.1.3官方文档

    四,后面会对认证过程,以及如何认证的进行详细说明。


    完整代码:http://download.csdn.net/detail/honghailiang888/9705858

    或 https://github.com/honghailiang/SpringMango

    
    
    
    
    
    

    你可能感兴趣的:(java,架构,Spring,Spring应用)