English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
「メモリ化する」機能を使用すると、ユーザーは再ログインしなくてもアプリケーションにアクセスできます。ユーザーのログインセッションはブラウザを閉じると終了し、ユーザーがブラウザを再開してアプリケーションにアクセスすると、再ログインの指示が出されます。
しかし「メモリ化する」機能を使用して再ログインを避けることができます。ユーザーの認証情報はCookieやデータベースに保存され、ユーザーを識別するために使用されます。
以下の例でこの認証を実現しています。一例を見てみましょう。
まず、Mavenプロジェクトを作成し、プロジェクトの詳細情報を提供します。
最初は、プロジェクトはこんな感じでした:
プロジェクトをSpringセキュリティを実現するために設定します。以下の4つのJavaファイルが必要です。まず、パッケージを作成します 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; } }
//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-generated method stub return null; } @Override protected String[] getServletMappings() { return new String[] {"/"}; } }
//SecurityWebApplicationInitializer.java
package com.w3codebox; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
//WebSecurityConfig.java
このクラスでは、ユーザーを生成し認証を行うことも行います。configure()メソッド内のRememberMe()メソッドは、ユーザーの認証情報を記憶し保存する責任があります。
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.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @EnableWebSecurity @ComponentScan("com.w3codebox") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withDefaultPasswordEncoder() .username("admin").password("admin123").roles("ADMIN").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(). antMatchers("/index", "/user","/").permitAll() .antMatchers("/admin").authenticated() .and() .formLogin() .loginPage("/login) .and() .rememberMe() .key("rem-me-キー .rememberMeParameter("remember") // これはログインページのチェックボックスの名前です .rememberMeCookieName("rememberlogin") // これはクッキーの名前です .tokenValiditySeconds(100) // 秒数 .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } }
の com.w3codebox.controller パッケージ内にコントローラーHomeControllerを生成してください。コントローラーコードを参照してください。
//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 = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping(value = "/admin", method = RequestMethod.GET) public String admin() { return "admin"; } }
ビュー(JSPページ)を作成して、出力をブラウザに生成します。
//index.jsp
<html> <head> <title>ホームページ</title> </head> <body> Welcome to w3codebox! <br> <br> <a href="admin">Admin ログイン</a> </body> </html>
//admin.jsp
<html> <head> <meta http-equiv-equiv="Content-Type-Type" content="text/html; charset=UTF-8-8"> <title>ホームページ</title> </head> <body> Welcome Admin! ? <a href="logout">logout</a> </body> </html>
//login.jsp
これは私たちのカスタムログインページであり、そこに「メモリーメ」チェックボックスを追加しました。コードを確認してください。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:url value="/login" var="loginUrl"/> <form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <p> Invalid username and password. </p> </c:if> <c:if test="${param.logout != null}"> <p> You have been logged out. </p> </c:if> <p> <label for="username">Username</label> <input type="text" id="username" name="username"/> </p> <p> <label for="password">Password</label> <input type="password" id="password" name="password"/> </p> <p> <label for="remember"> Remember me</label> <input type="checkbox" name="remember" /> </p> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button type="submit" class="btn">ログイン</button>/button> </form>
以下は、すべての必要な依存関係を含むpom.xmlファイルです。
//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.w</groupId>3codebox/groupId> <artifactId>springrememberme</artifactId>/artifactId> <version>0.0.1-SNAPSHOT/version> <packaging>war</packaging>/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>/groupId> <artifactId>spring</artifactId>-webmvc/artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId>/groupId> <artifactId>spring</artifactId>-security-web/artifactId> <version>5.0.0.RELEASE/version> </dependency> <dependency> <groupId>org.springframework.security</groupId>/groupId> <artifactId>spring</artifactId>-security-core/artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --> <dependency> <groupId>org.springframework.security</groupId>/groupId> <artifactId>spring</artifactId>-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</artifactId>-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </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>
すべてのファイルを追加した後、プロジェクト構造は以下のようになります:
出力:
Admin ログインリンクをクリックしてログインします。
見てください、私たちが 「メモリーメディア」をクリック チェックボックス
URLをコピー http://localhost:8080/springrememberme/admin そして、ブラウザを完全に閉じます。別のブラウザを開き、コピーしたURLを貼り付けます。
参照してください。ログインを要求せずに同じページにログインします。なぜなら、ログイン中に「メモリーメディア」ボタンを選択したからです。