【Spring實戰】----spring security4.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官方文件