Spring Security為jsp頁面提供了自己的標記。這些標簽用于訪問JSP中的安全信息并應用安全約束。
以下標簽用于保護應用程序的視圖層。
授權標簽 身份驗證標簽 Accesscontrollist標記 Csrfinput標簽 CsrfMetaTags標簽
此標簽用于授權目的。此標簽評估并檢查請求是否被授權。
它使用兩個屬性 access 和 URL 來檢查請求授權。我們可以通過用戶角色來評估此標簽。
僅當屬性滿足時,顯示在該標簽內的內容才會顯示。例如。
<sec:authorize access="hasRole('ADMIN')"> It will display only is user is admin </sec:authorize>
此標簽用于訪問存儲在安全上下文中的身份驗證。如果Authentication是UserDetails對象的實例,則可用于獲取當前用戶的詳細信息。例如。
<sec:authentication property="principal.username">
該標記與Spring Security的ACL模塊一起使用。它檢查指定域的必需權限列表。僅當當前用戶擁有所有權限時,它才會執(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>
此標簽用于為HTML表單創(chuàng)建CSRF令牌。要使用它,請確保已啟用CSRF保護。我們應該將此標簽放在 標簽內以創(chuàng)建CSRF令牌。例如。
<form method="post" action="/some/action"> <sec:csrfInput /> Name:<br /> <input type="text" name="username" /> ... </form>
它插入包含CSRF令牌,表單字段,標頭名稱和CSRF令牌值的元標簽。這些值對于在應用程序中的JavaScript中設置CSRF令牌很有用。
該標簽應放在HTML 標簽內。
要實現這些標簽中的任何一個,我們必須在應用程序中具有spring security taglib jar。也可以使用以下Maven依賴項將其添加。
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>5.0.4.RELEASE</version> </dependency>
在JSP頁面中,我們可以使用以下聲明來使用taglib。
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
現在,讓我們看一個在Spring Security Maven項目中實現這些標簽的示例。
我們正在使用STS(Spring工具套件)來創(chuàng)建項目。參見示例。
單擊 完成 >按鈕,它將創(chuàng)建一個如下所示的Maven項目:
要在Spring MVC應用程序中配置Spring Security,請將以下四個文件放入 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用于設置視圖文件的視圖位置后綴。
//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調度程序。
//SecurityWebApplicationInitializer.java
package com.nhooo; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
再創(chuàng)建一個用于創(chuàng)建用戶并在用戶可訪問性上應用身份驗證和授權的類。
//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")); } }
現在,創(chuà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)文件以向用戶顯示輸出。我們已經創(chuàng)建了三個JSP文件,請參見下文。
//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
在管理頁面中,我們使用了authorize標簽,該標簽僅在滿足給定角色時才進行評估。
<%@ 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>
我們的項目包含以下構建應用程序所需的依賴項。
//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>
添加所有這些文件后,我們的項目如下所示:
右鍵單擊項目,然后選擇 在服務器上運行。它向瀏覽器顯示以下輸出。
通過提供在 AppSecurityConfig 文件中設置的憑據,單擊用戶并登錄。
成功登錄后,它將顯示如下所示的管理頁面。在這里,請注意,由于登錄用戶具有USER角色,因此未顯示寫入authorize標記內的內容。
注銷,現在通過提供管理員憑據以admin身份登錄。
以admin身份登錄后,請參閱這次的authorize標簽進行評估,并顯示以下輸出。