个性化阅读
专注于IT技术分析

Spring Security实现“记住我”功能示例图解

记住我是一项功能, 允许用户无需重新登录即可访问应用程序。用户的登录会话在关闭浏览器后终止, 并且如果用户再次通过打开浏览器访问该应用程序, 则提示登录。

但是我们可以使用”记住我”功能来避免重新登录。它将用户的身份存储到Cookie或数据库中, 并用于标识用户。

我们将其实现到以下示例中。让我们来看一个例子。

创建一个Maven项目

首先创建一个Maven项目并提供项目详细信息。

Spring Security记住我

最初, 项目如下所示:

Spring Security记住我2

Spring安全配置

配置项目以实现spring安全。它需要以下四个Java文件。首先创建一个包com.srcmini并将所有文件放入其中。

// AppConfig.java

package com.srcmini;
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.srcmini.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.srcmini;  
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.srcmini;  
import org.springframework.security.web.context.*;        
	public class SecurityWebApplicationInitializer  
        extends AbstractSecurityWebApplicationInitializer {  
    }

// WebSecurityConfig.java

在此类中, 我们还将创建用户并进行身份验证。 configure()方法内部的RememberMe()方法负责记住和存储用户身份。

package com.srcmini;
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.srcmini")  
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) // remember for number of seconds
	  .and()
	  .logout()
	  .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));  
}  
}

控制者

在com.srcmini.controller包内创建一个控制器HomeController。请参阅控制器代码。

// HomeController.java

package com.srcmini.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>Home Page</title>  
</head>  
<body>  
Welcome to srcmini! <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>
	<input type="hidden"                        
		name="${_csrf.parameterName}"
		value="${_csrf.token}"/>
	<button type="submit" class="btn">Log in</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.srcmini</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>

项目结构

添加所有文件后, 项目结构如下所示:

Spring Security记住我3

运行服务器

输出

Spring Security记住我4

单击管理员登录链接并登录。

Spring Security记住我5

瞧, 我们已经点击了记住我复选框。

Spring Security记住我6

复制URL:http:// localhost:8080 / springrememberme / admin并完全关闭浏览器。在第二次打开浏览器后, 粘贴复制的URL。

请参阅, 它不要求登录, 也不需要我们登录同一页面。因为我们确实在登录时检查了”记住我”按钮。

赞(0) 打赏
未经允许不得转载:srcmini » Spring Security实现“记住我”功能示例图解
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏