English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Функция "Запомнить меня" в Spring Security

Функция "Запомнить меня" позволяет пользователю получить доступ к приложению без повторного входа. Сессия входа пользователя завершается после закрытия браузера, и если пользователь снова откроет браузер и зайдет в приложение, ему будет предложено войти.

Но мы можем использовать функцию "Запомнить меня", чтобы избежать повторного входа. Эта функция хранит идентичность пользователя в Cookie или базе данных и используется для идентификации пользователя.

Мы реализуем эту идентичность в следующем примере. Давайте посмотрим на пример.

Создание проекта Maven

Сначала создайте проект Maven и предоставьте подробную информацию о проекте.



Вначале проект может выглядеть так:



Конфигурация Spring Security

Настройте проект для использования Spring Security. Для этого потребуется следующие четыре Java файла. Сначала создайте пакет com.w3codebox и все файлы поместите в нее.

//AppConfig.java

пакет 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

пакет com.w3codebox;  
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
public class MvcWebApplicationInitializer extends  
        AbstractAnnotationConfigDispatcherServletInitializer {  
    @Override  
    protected Class<?>[] getRootConfigClasses() {  
        возврат new Class[] { WebSecurityConfig.class };  
    }  
    @Override  
    защищенный Class<?>[] getServletConfigClasses() {  
        // Todo Auto-generated method stub  
        возврат null;  
    }  
    @Override  
    защищенный String[] getServletMappings() {  
        возврат new String[] { "/" };  
    }  
}

//SecurityWebApplicationInitializer.java

пакет com.w3codebox;  
импорт org.springframework.security.web.context.*;        
    публичный класс SecurityWebApplicationInitializer  
        расширяет AbstractSecurityWebApplicationInitializer {  
    }

//WebSecurityConfig.java

В этом классе мы также создадим пользователей и будем выполнять аутентификацию. Метод RememberMe() в методе configure() отвечает за запоминание и хранение идентификации пользователя.

пакет com.w3codebox;
импорт org.springframework.context.annotation.*;    
импорт org.springframework.security.config.annotation.web.builders.HttpSecurity;  
импорт org.springframework.security.config.annotation.web.configuration.*;  
импорт org.springframework.security.core.userdetails.*;  
импорт org.springframework.security.provisioning.InMemoryUserDetailsManager;
импорт 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") // это имя чекбокса на странице входа
      .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>  
Добро пожаловать в w3codebox! <br> <br>
<a href="admin">Вход администратора</a>  
</body>  
</html>

//admin.jsp

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Стартовая страница</title>  
</head>  
<body>  
Добро пожаловать, Администратор! ?
<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>
            Неправильное имя пользователя и пароль.
        </p>
    </c:if>
    <c:if test="${param.logout != null}">       
        <p>
            Вы были выведены из системы.
        </p>
    </c:if>
    <p>
        <label for="username">Имя пользователя</label>
        <input type="text" id="username" name="username"/>   
    </p>
    <p>
        <label for="password">Пароль</label>
        <input type="password" id="password" name="password"/>    
    </p>
    <p>
        <label for="remember"> Запомнить меня</label>
        <input type="checkbox" name="remember" />
    </p>
    <input type="hidden"                        
        name="${_csrf.parameterName}"
        value="${_csrf.token}"/>
    <button type="submit" class="btn">Войти</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.w3codebox</groupId>
  <artifactId>springrememberme</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-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>  
</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.

См. также, он не требует входа и把我们登录 на одну страницу. Porque realmente marcamos o botão " Lembrar-me " ao nos logar.