當使用者通過認證,意即登入後,除了可以存取網頁資訊外,某些網頁元素是可以透過Spring Security Tag來決定使用者是否可以看的到,但今天先以最簡單為例,登入後可以看到logout的連結,並顯示Hi, 登入帳號名稱並顯示logout連結,如果未登錄導覽列顯示login連結,要使用Spring Security Tag,必須先加入以下dependency
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${security.version}</version>
<scope>compile</scope>
</dependency>
<properties>
<security.version>3.2.5.RELEASE</security.version>
</properties>
先修改導覽列,修改base.jsp code如下:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
....
<nav class="navigation-bar dark">
<nav class="navigation-bar-content container">
.....
<li><a href="#">About Us</a></li>
</ul>
<sec:authorize access="authenticated" var="authenticated" />
<c:choose>
<c:when test="${authenticated}">
<div class="element place-right">
<p class="text-right fg-white">
Hi,
<sec:authentication property="name" />
<a href="<spring:url value="/logout"/>"
class="button link">Log out</a>
</p>
</div>
</c:when>
<c:otherwise>
<a class="element place-right" href="<spring:url value="/login"/>">Log in</a>
</c:otherwise>
</c:choose>
<span class="element-divider place-right"></span>
</nav>
</nav>
....
<sec:authorize access="">標籤用來設定存取權限,這邊用的關鍵字authenticated,意思是只要登過帳號驗證,即可有權限存取,搭配<c:choose>,當使用者登入,即authenticated,則顯示Hi, 使用者名稱,使用者名稱變數,可以透過<sec:authorize property=name/>取得,並接著一個logout的button連結,其他其況(<c:otherwise>)則顯示login連結。
啟動Server,未登入畫面
以admin 帳號登入,畫面如下
同樣的本文也可以用<c:choose>換掉原本的文字
Logout的部分,參考官方文件
我自己寫一個簡單的controller,其code如下:
@RequestMapping(value="/logout", method=RequestMethod.GET)
public String logout(HttpServletRequest req) throws ServletException{
req.logout();
return "redirect:/";
}
Console log:
23:56:56 [http-nio-8080-exec-4] DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/SpringMVC/logout]
23:56:56 [http-nio-8080-exec-4] RequestMappingHandlerMapping - Looking up handler method for path /logout
23:56:56 [http-nio-8080-exec-4] RequestMappingHandlerMapping - Returning handler method [public java.lang.String tw.blogger.springtech.springmvc.controller.DefaultController.logout(javax.servlet.http.HttpServletRequest) throws javax.servlet.ServletException]
23:56:56 [http-nio-8080-exec-4] DispatcherServlet - Last-Modified value for [/SpringMVC/logout] is: -1
23:56:56 [http-nio-8080-exec-4] ContentNegotiatingViewResolver - Requested media types are [text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
23:56:56 [http-nio-8080-exec-4] ContentNegotiatingViewResolver - Returning redirect view [org.springframework.web.servlet.view.RedirectView: name 'redirect:/'; URL [/]]
23:56:56 [http-nio-8080-exec-4] DispatcherServlet - Rendering view [org.springframework.web.servlet.view.RedirectView: name 'redirect:/'; URL [/]] in DispatcherServlet with name 'dispatcher'
23:56:56 [http-nio-8080-exec-4] DispatcherServlet - Successfully completed request