Spring Security為jsp頁(yè)面提供了自己的標(biāo)記。這些標(biāo)簽用于訪問JSP中的安全信息并應(yīng)用安全約束。
以下標(biāo)簽用于保護(hù)應(yīng)用程序的視圖層。
授權(quán)標(biāo)簽 身份驗(yàn)證標(biāo)簽 Accesscontrollist標(biāo)記 Csrfinput標(biāo)簽 CsrfMetaTags標(biāo)簽
此標(biāo)簽用于授權(quán)目的。此標(biāo)簽評(píng)估并檢查請(qǐng)求是否被授權(quán)。
它使用兩個(gè)屬性 access 和 URL 來(lái)檢查請(qǐng)求授權(quán)。我們可以通過用戶角色來(lái)評(píng)估此標(biāo)簽。
僅當(dāng)屬性滿足時(shí),顯示在該標(biāo)簽內(nèi)的內(nèi)容才會(huì)顯示。例如。
<sec:authorize access="hasRole('ADMIN')"> It will display only is user is admin </sec:authorize>
此標(biāo)簽用于訪問存儲(chǔ)在安全上下文中的身份驗(yàn)證。如果Authentication是UserDetails對(duì)象的實(shí)例,則可用于獲取當(dāng)前用戶的詳細(xì)信息。例如。
<sec:authentication property="principal.username">
該標(biāo)記與Spring Security的ACL模塊一起使用。它檢查指定域的必需權(quán)限列表。僅當(dāng)當(dāng)前用戶擁有所有權(quán)限時(shí),它才會(huì)執(zhí)行。例如。
<sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}"> if user has all the permissions represented by the values "1" or "2" on the given object. </sec:accesscontrollist>
此標(biāo)簽用于為HTML表單創(chuàng)建CSRF令牌。要使用它,請(qǐng)確保已啟用CSRF保護(hù)。我們應(yīng)該將此標(biāo)簽放在 標(biāo)簽內(nèi)以創(chuàng)建CSRF令牌。例如。
<form method="post" action="/some/action"> <sec:csrfInput /> Name:<br /> <input type="text" name="username" /> ... </form>
它插入包含CSRF令牌,表單字段,標(biāo)頭名稱和CSRF令牌值的元標(biāo)簽。這些值對(duì)于在應(yīng)用程序中的JavaScript中設(shè)置CSRF令牌很有用。
該標(biāo)簽應(yīng)放在HTML 標(biāo)簽內(nèi)。
要實(shí)現(xiàn)這些標(biāo)簽中的任何一個(gè),我們必須在應(yīng)用程序中具有spring security taglib jar。也可以使用以下Maven依賴項(xiàng)將其添加。
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>5.0.4.RELEASE</version> </dependency>
在JSP頁(yè)面中,我們可以使用以下聲明來(lái)使用taglib。
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
現(xiàn)在,讓我們看一個(gè)在Spring Security Maven項(xiàng)目中實(shí)現(xiàn)這些標(biāo)簽的示例。
我們正在使用STS(Spring工具套件)來(lái)創(chuàng)建項(xiàng)目。參見示例。
單擊 完成 >按鈕,它將創(chuàng)建一個(gè)如下所示的Maven項(xiàng)目:
要在Spring MVC應(yīng)用程序中配置Spring Security,請(qǐng)將以下四個(gè)文件放入 com.nhooo中文件夾。
AppConfig.java
package com.nhooo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.nhooo.controller.*" }) public class AppConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
AppConfig用于設(shè)置視圖文件的視圖位置后綴。
//MvcWebApplicationInitializer.java
package com.nhooo; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { WebSecurityConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // TOdo Auto-generated method stub return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
該類用于初始化servlet調(diào)度程序。
//SecurityWebApplicationInitializer.java
package com.nhooo; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
再創(chuàng)建一個(gè)用于創(chuàng)建用戶并在用戶可訪問性上應(yīng)用身份驗(yàn)證和授權(quán)的類。
//WebSecurityConfig.java
package com.nhooo; import org.springframework.context.annotation.*; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.*; import org.springframework.security.core.userdetails.*; import org.springframework.security.core.userdetails.User.UserBuilder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @EnableWebSecurity @ComponentScan("com.nhooo") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { // ensure the passwords are encoded properly UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(users.username("mohan").password("1mohan23").roles("USER").build()); manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(). antMatchers("/index","/").permitAll() .antMatchers("/admin","/user").authenticated() .and() .formLogin() .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } }
現(xiàn)在,創(chuàng)建一個(gè)控制器來(lái)處理請(qǐng)求并做出響應(yīng)。
//HomeController.java
package com.nhooo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { @RequestMapping(value="/", method=RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value="/user", method=RequestMethod.GET) public String user() { return "admin"; } @RequestMapping(value="/admin", method=RequestMethod.GET) public String admin() { return "admin"; } }
創(chuàng)建視圖(jsp)文件以向用戶顯示輸出。我們已經(jīng)創(chuàng)建了三個(gè)JSP文件,請(qǐng)參見下文。
//index.jsp
<html> <head> <title>Home Page</title> </head> <body> <a href="user">User</a> <a href="admin">Admin</a> <br> <br> Welcome to Nhooo! </body> </html>
//user.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> Welcome to user page! </body> </html>
//admin.jsp
在管理頁(yè)面中,我們使用了authorize標(biāo)簽,該標(biāo)簽僅在滿足給定角色時(shí)才進(jìn)行評(píng)估。
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> Welcome to admin page! <a href="logout">logout</a> <br><br> <security:authorize access="hasRole('ADMIN')"> Hello ADMIN </security:authorize> <security:csrfInput/> </body> </html>
我們的項(xiàng)目包含以下構(gòu)建應(yīng)用程序所需的依賴項(xiàng)。
//pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.nhooo</groupId> <artifactId>springtaglibrary</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
添加所有這些文件后,我們的項(xiàng)目如下所示:
右鍵單擊項(xiàng)目,然后選擇 在服務(wù)器上運(yùn)行。它向?yàn)g覽器顯示以下輸出。
通過提供在 AppSecurityConfig 文件中設(shè)置的憑據(jù),單擊用戶并登錄。
成功登錄后,它將顯示如下所示的管理頁(yè)面。在這里,請(qǐng)注意,由于登錄用戶具有USER角色,因此未顯示寫入authorize標(biāo)記內(nèi)的內(nèi)容。
注銷,現(xiàn)在通過提供管理員憑據(jù)以admin身份登錄。
以admin身份登錄后,請(qǐng)參閱這次的authorize標(biāo)簽進(jìn)行評(píng)估,并顯示以下輸出。