English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Spring SecurityはJSPページに独自のタグを提供します。これらのタグはJSP内のセキュリティ情報にアクセスし、セキュリティ制約を適用するために使用されます。
以下のタグはアプリケーションのビューレイヤーを保護するために使用されます。
認証タグ 認証タグ Accesscontrollistマーク Csrfinputタグ CsrfMetaTagsタグ
このタグは認証のために使用されます。このタグはリクエストが認証されているかどうかを評価し、チェックします。
このタグは2つの属性を使用して動作します アクセス および URL リクエストの認証をチェックするために使用されます。ユーザーの役割を通じてこのタグを評価できます。
属性が満たされている場合にのみ、このタグ内の内容が表示されます。例えば。
<sec:authorize access="hasRole('ADMIN')"> ユーザーが管理者の場合にのみ表示されます </sec:authorize>
このタグは安全上下文に保存されている認証にアクセスするために使用されます。AuthenticationがUserDetailsオブジェクトのインスタンスの場合、現在のユーザーの詳細情報を取得するために使用できます。例えば。
<sec:authentication property="principal.username">
このマークはSpring SecurityのACLモジュールと一緒に使用されます。指定されたエリアの必要な権限リストをチェックします。現在のユーザーがすべての権限を持っている場合にのみ実行されます。例えば。
<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フォームにCSRFトークンを作成するために使用されます。使用する場合は、CSRF保護が有効になっていることを確認してください。このタグを以下に配置する必要があります。 タグ内で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ツールキット)でプロジェクトを作成しています。参照してください。
クリック 完了 >ボタンをクリックすると、以下のように表示されるMavenプロジェクトが作成されます:
Spring MVCアプリケーションでSpring Securityを構成するには、以下の四个ファイルを配置してください com.w3codebox中フォルダー。
AppConfig.java
package com.w3codebox; 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.w3codebox.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.w3codebox; 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-生成されたメソッドスタブ return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
このクラスはservletスケジューラーの初期化に使用されます。
//SecurityWebApplicationInitializer.java
package com.w3codebox; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
再创建一个用于创建用户并在用户可访问性上应用身份验证和承認のクラス。
//WebSecurityConfig.java
package com.w3codebox; 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.w3codebox) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { // パスワードが適切にエンコードされることを確認します 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")); } }
現在、リクエストを処理し、応答するコントローラーを作成します。
//HomeController.java
package com.w3codebox.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"; } }
作成視覚化(jsp)ファイルをユーザーに表示するため、視覚化を行いました。以下に示すように、3つの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 w3codebox! </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.w3codebox</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 タグの評価を確認し、以下の出力を表示してください。