鍍金池/ 教程/ Java/ Spring Security標(biāo)簽庫(kù)顯示視圖
Spring Security自定義表單登錄注釋示例
Spring Secrity與Hibernate基于角色登錄實(shí)例
Spring Security自定義表單登錄實(shí)例
Secure Spring REST API使用OAuth2
Spring Security與Hibernate整合以及XML實(shí)例
Spring Security入門程序示例
Spring Security+Hibernate密碼編碼器Bcrypt實(shí)例
Spring Security標(biāo)簽庫(kù)顯示視圖
Spring Security基于角色登錄實(shí)例
Spring Security使用@PreAuthorize,@PostAuthorize, @Secured方法安全
Secure Spring REST API使用基本認(rèn)證
Spring Security入門程序注釋示例
Spring Security+Hibernate記住我實(shí)例
Spring MVC4 + Spring Security4 + Hibernate實(shí)例
Spring Security注銷登錄實(shí)例
AngularJS+Spring Security使用基本身份驗(yàn)證
Spring Security教程

Spring Security標(biāo)簽庫(kù)顯示視圖

本教程介紹了如何保護(hù)視圖層,基于已登錄用戶的角色,使用Spring Security標(biāo)簽來(lái)顯示/隱藏 Spring MVC Web應(yīng)用程序的JSP/視圖。
完整的工程結(jié)構(gòu)如下所示 - 


首先,為了使用Spring Security標(biāo)簽,我們需要在pom.xml中包括 spring-security-taglibs 標(biāo)記庫(kù)的依賴庫(kù),如下圖所示:
<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>4.0.1.RELEASE</version>
		</dependency>
然后在下一步在 視圖/JSP 包括這些標(biāo)簽庫(kù)。如下代碼所示 -
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

最后,我們就可以使用Spring Security表達(dá)式類似 hasRole,hasAnyRole 等。在視圖中,如下圖所示:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Welcome page</title>
</head>
<body>
	Dear <strong>${user}</strong>, Welcome to Home Page.
	<a href="<c:url value="/logout" />">Logout</a>

	<br/>
	<br/>
	<div>
		<label>View all information| This part is visible to Everyone</label>
	</div>

	<br/>
	<div>
		<sec:authorize access="hasRole('ADMIN')">
			<label><a href="#">Edit this page</a> | This part is visible only to ADMIN</label>
		</sec:authorize>
	</div>

	<br/>
	<div>
		<sec:authorize access="hasRole('ADMIN') and hasRole('DBA')">
			<label><a href="#">Start backup</a> | This part is visible only to one who is both ADMIN & DBA</label>
		</sec:authorize>
	</div>
</html>
這里就是需要基于角色這個(gè)有選擇地顯示/隱藏視圖片段,使用Spring Security表達(dá)式在視圖中。
以下是用于這個(gè)例子的 Security 配置:
package com.yiibai.springsecurity.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	
	@Autowired
	public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("yiibai").password("123456").roles("USER");
		auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
		auth.inMemoryAuthentication().withUser("dba").password("123456").roles("ADMIN","DBA");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
	  
	  http.authorizeRequests()
	  	.antMatchers("/", "/home").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
	  	.and().formLogin().loginPage("/login")
	  	.usernameParameter("ssoId").passwordParameter("password")
	  	.and().exceptionHandling().accessDeniedPage("/Access_Denied");
	}
}
上面的安全配置基于XML配置格式如下所示:
<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-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
     
    <http auto-config="true" >
        <intercept-url pattern="/"     access="hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')" />
        <intercept-url pattern="/home" access="hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')" />
        <form-login  login-page="/login" 
                     username-parameter="ssoId" 
                     password-parameter="password" 
                     authentication-failure-url="/Access_Denied" />
    </http>
 
    <authentication-manager >
        <authentication-provider>
            <user-service>
                <user name="yiibai"  password="123456"  authorities="ROLE_USER" />
                <user name="admin" password="123456" authorities="ROLE_ADMIN" />
                <user name="dba"   password="123456" authorities="ROLE_ADMIN,ROLE_DBA" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
     
    
</beans:beans>

下面是控制器的完整代碼,如下所示 -

package com.yiibai.springsecurity.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWorldController {

	
	@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
	public String homePage(ModelMap model) {
		model.addAttribute("user", getPrincipal());
		return "welcome";
	}

	@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
	public String accessDeniedPage(ModelMap model) {
		model.addAttribute("user", getPrincipal());
		return "accessDenied";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage() {
		return "login";
	}

	@RequestMapping(value="/logout", method = RequestMethod.GET)
	public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null){    
			new SecurityContextLogoutHandler().logout(request, response, auth);
		}
		return "redirect:/login?logout";
	}

	private String getPrincipal(){
		String userName = null;
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			userName = ((UserDetails)principal).getUsername();
		} else {
			userName = principal.toString();
		}
		return userName;
	}

}
應(yīng)用程序的其余部分代碼和這個(gè)系列的其他教程文章是相同的。

部署和運(yùn)行

如需要自己動(dòng)手實(shí)踐,可在文章底部提供的下載鏈接并點(diǎn)擊下載本示例代碼,這個(gè)項(xiàng)目的完整代碼。它是在Servlet 3.0的容器(Tomcat7/8,本文章使用 Tomcat7)上構(gòu)建和部署運(yùn)行的。
打開(kāi)您的瀏覽器,在地址欄中輸入網(wǎng)址:http://localhost:8080/SpringSecurityTaglibs,默認(rèn)的頁(yè)面將顯示(提示登錄頁(yè)面)如下 - 

提供用戶登錄憑據(jù)(用戶名及密碼),首先我們使用 yiibai 這個(gè)用戶名登錄如下所示 -

登錄成功后可以看到,有限的信息顯示頁(yè)面上,如下圖中所示 - 

現(xiàn)在點(diǎn)擊注銷,并使用管理員角色登錄,所下圖中所示 - 

提交登錄成功后,你會(huì)看到使用ADMIN角色的操作訪問(wèn),如下圖中所示 - 

現(xiàn)在注銷登錄,然后使用 DBA 角色登錄,如下圖中所示 - 

提交登錄成功后,你會(huì)看到與DBA角色相關(guān)的操作訪問(wèn)。

全部就這樣(包教不包會(huì))。下一篇教程文章將我們學(xué)習(xí)如何使用基于角色登錄。這意味著可根據(jù)自己分配的角色,在登錄成功后用戶將重定向到不同的URL。

下載代碼

參考