Spring Security登录和注销模块示例

Spring Security提供了登录和注销功能,我们可以在我们的应用程序中使用它。它有助于创建安全的Spring应用程序。

在这里,我们将创建一个带有Spring Security的Spring MVC应用程序,并实现登录和注销功能。

首先,我们创建了一个Maven项目,并在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>cn.javatiku</groupId>  
  <artifactId>springSecurityLoginOut</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.0.RELEASE</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework.security</groupId>  
        <artifactId>spring-security-config</artifactId>  
        <version>5.0.0.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配置

接下来,我们创建了配置文件来启用登录功能,并仅允许授权用户访问。

本项目包含以下四个Java文件。

AppConfig.java

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

WebSecurityConfig.java

package cn.javatiku;  
import org.springframework.context.annotation.*;  
//import org.springframework.security.config.annotation.authentication.builders.*;  
import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
import org.springframework.security.config.annotation.web.configuration.*;  
import org.springframework.security.core.userdetails.User;  
import org.springframework.security.core.userdetails.UserDetailsService;  
import org.springframework.security.provisioning.InMemoryUserDetailsManager;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  
@EnableWebSecurity  
@ComponentScan("cn.javatiku")  
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
      
    @Bean  
    public UserDetailsService userDetailsService() {  
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();  
        manager.createUser(User.withDefaultPasswordEncoder()  
        .username("irfan").password("khan").roles("ADMIN").build());  
        return manager;  
    }  
      
    @Override  
    protected void configure(HttpSecurity http) throws Exception {  
                  
        http                              
        .authorizeRequests()  
            .anyRequest().hasRole("ADMIN")  
            .and().formLogin().and()  
        .httpBasic()  
        .and()  
        .logout()  
        .logoutUrl("/j_spring_security_logout")  
        .logoutSuccessUrl("/")  
        ;  
    }  
}  

控制器

HomeController: 用于处理用户请求的控制器。

package cn.javatiku.controller;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.security.core.Authentication;  
import org.springframework.security.core.context.SecurityContextHolder;  
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;  
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="/logout", method=RequestMethod.GET)  
    public String logoutPage(HttpServletRequest request, HttpServletResponse response) {  
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();  
        if (auth != null){      
           new SecurityContextLogoutHandler().logout(request, response, auth);  
        }  
         return "redirect:/";  
     }  
}  

视图

我们有一个名为index.jsp的JSP文件,其中包含以下代码。

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
"http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Home</title>  
</head>  
<body>  
<h3> Hello ${pageContext.request.userPrincipal.name}, </h3>  
<h4>Welcome to javatiku! </h4>  
<a href="<c:url value='/logout' />">Click here to logout</a>  
</body>  
</html>  

项目结构

创建上述文件后,我们的项目结构如下所示:

spring-security-login-logout.png

输出:

在使用Apache Tomcat运行时,它会在浏览器中生成以下输出。

spring-security-login-logout1.png

现在,提供用户凭据以成功登录。

spring-security-login-logout2.png

成功登录后,它会显示主页,如下所示。

spring-security-login-logout3.png

在这里,我们创建了一个注销链接,可以使用该链接注销。让我们来验证并从应用程序注销。

spring-security-login-logout4.png

然后它会重定向回登录页面。

spring-security-login-logout5.png

好了,我们已经成功创建了一个使用Spring Security实现登录和注销功能的Spring MVC应用程序。

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想