【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

<!-- Spring-security -->
	<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>

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

<!-- Spring-security -->
	<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>
	
	<!--sitemesh装饰器放在spring security过来器的后面,以免装饰器页中的security不起作用-->
	<filter>
		<filter-name>sitemesh</filter-name>
		<filter-class>
			org.sitemesh.config.ConfigurableSiteMeshFilter
		</filter-class>
			<init-param>
			<param-name>ignore</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>sitemesh</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

装饰器页面中的使用

<sec:authorize access="!hasRole('ROLE_USER')">
        			<li>你好,欢迎来到Mango!<a href="<c:url value='/login'/>" class="current">登录</a></li>
        		</sec:authorize>
        		<sec:authorize access="hasRole('ROLE_USER')">
        			<li><sec:authentication property="principal.username"/>欢迎光临Mango!<a href="<c:url value='/logout'/>" class="current">退出</a></li>
        		</sec:authorize>

三、security配置文件配置

applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="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.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
		
	<http auto-config="true" use-expressions="true" >
		<form-login 
			login-page="/login"
            authentication-failure-url="/login?error" 
            login-processing-url="/login"
            always-use-default-target="false"
            authentication-success-handler-ref="myAuthenticationSuccessHandler" />   
         <!-- 认证成功用自定义类myAuthenticationSuccessHandler处理 -->
         
         <logout logout-url="/logout" 
				logout-success-url="/" 
				invalidate-session="true"
				delete-cookies="JSESSIONID"/>
		
		<csrf disabled="true" />
		<intercept-url pattern="/order/*" access="hasRole('ROLE_USER')"/>
	</http>
	
	<!-- 使用自定义类myUserDetailsService从数据库获取用户信息 -->
	<authentication-manager>  
        <authentication-provider user-service-ref="myUserDetailsService">  
        	<!-- 加密 -->
            <password-encoder hash="md5">
            </password-encoder>
        </authentication-provider>
    </authentication-manager>
	
</beans:beans>

这里配置了自定义登录界面/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"%>
<!DOCTYPE html>
<html>
<head>
    <title>Mango-Login</title>
	<meta name="menu" content="home" />    
</head>

<body>

<h1>请登录!</h1>

<div style="text-align:center">
	<form action="<c:url value='/login' />" method="post">
		<c:if test="${not empty error}">
			<p style="color:red">${error}</p>
		</c:if>
      <table>
         <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"/></td>
         </tr>
         <tr>
            <td>密码:</td>
            <td><input type="password" name="password"/></td>
         </tr>
         <tr>
            <td colspan="2" align="center">
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </td>
         </tr>
      </table>
   </form>
</div>

</body>
</html>

其中,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保护功能禁用<csrf disabled="true" />,防止页面中没有配置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







©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值