English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
"记住我" 기능은 사용자가 다시 로그인하지 않고도 애플리케이션에 액세스할 수 있도록 합니다. 사용자의 로그인 세션이 브라우저를 닫았을 때 종료되며, 사용자가 브라우저를 다시 열고 애플리케이션에 다시 액세스하면 로그인이 요청됩니다。
但是我们可以使用"记住我"功能来避免重新登录。它将用户의 신분을 Cookie나 데이터베이스에 저장하고, 사용자를 식별하기 위해 사용됩니다。
我们正在以下示例中实现该身份。让我们看一个实例。
首先创建一个Maven项目并提供项目详细信息。
最初,项目看起来像这样:
配置项目以实现spring安全。它需要以下四个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-key) .rememberMeParameter("remember") // it is name of checkbox at login page .rememberMeCookieName("rememberlogin") // it is name of the cookie .tokenValiditySeconds(100) // remeber for number of seconds .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"; } }
뷰(HTML 페이지)를 생성하여 출력을 브라우저로 전송합니다。
//index.jsp
<html> <head> <title>Home Page</title> </head> <body> Welcome to w3codebox! <br> <br> <a href="admin">Admin login</a> </body> </html>
//admin.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</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> <인풋 type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <버튼 type="submit" class="btn">로그인</버튼> </폼>
아래는 우리의 pom.xml 파일로, 모든 필요한 의존성이 포함되어 있습니다.
//pom.xml
<프로젝트 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-인스턴스" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <모델버전>4.0.0</모델버전> <그룹ID>com.w3codebox/<groupId>org.apache.maven.plugins <아티펙트ID>springrememberme/plugin< <버전>0.0.1-스냅샷/version> <패키징>war</패키징> <프로퍼티> <maven.compiler.target>1<version>8</maven.compiler.target> <maven.compiler.source>1<version>8</maven.compiler.source> </프로퍼티> <의존성> <그룹ID>org.springframework</<groupId>org.apache.maven.plugins <아티펙트ID>spring-웹.mvc/plugin< artifactId>5.0.2.RELEASE</version> </<artifactId>jstl <그룹ID>org.springframework.security</<groupId>org.apache.maven.plugins <아티펙트ID>spring-보안-웹/plugin< artifactId>5.0.0.RELEASE</version> </<artifactId>jstl <그룹ID>org.springframework.security</<groupId>org.apache.maven.plugins <아티펙트ID>spring-보안-코어/plugin< artifactId>5.0.4.RELEASE</version> </<artifactId>jstl <!-- https://mvnrepository.com/아티펙트/org.springframework.security/스프링-보안-구성 --> <그룹ID>org.springframework.security</<groupId>org.apache.maven.plugins <아티펙트ID>spring-보안-구성/plugin< artifactId>5.0.4.RELEASE</version> </<artifactId>jstl <!-- https://mvnrepository.com/아티펙트/javax.servlet/javax.servlet-api --> <dependency>/<groupId>org.apache.maven.plugins <아티펙트ID>javax.servlet-api</plugin< artifactId>3<version>1.0</version> <스코프>제공된</스코프> </<artifactId>jstl <dependency>/<groupId>org.apache.maven.plugins <groupId>javax.servlet/plugin< artifactId>1<version>2</version> </<artifactId>jstl </<dependency> <dependencies> <build> <plugins> <plugin>/<groupId>org.apache.maven.plugins <groupId>-<artifactId>maven-war/plugin< artifactId>2<version>6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
모든 파일을 추가한 후, 프로젝트 구조는 다음과 같습니다:
출력:
Admin 로그인 링크를 클릭하여 로그인하십시오.
보세요, 우리는 "기억해 주세요"를 클릭하십시오 체크박스
URL 복사 http://localhost:8080/springrememberme/admin 두 번째 브라우저를 열고 복사한 URL을 붙여넣습니다. 브라우저를 완전히 닫습니다.
보다 자세히 알아보세요. 로그인을 요청하지 않으며, "기억해 주세요" 버튼을 눌렀기 때문에 동일한 페이지에 로그인합니다.