Spring Security登录-注销模块示例

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

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

首先,我们创建了一个maven项目,并在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.nhooo</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 com.nhooo;
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.nhooo.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.nhooo;
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.nhooo;
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
    extends AbstractSecurityWebApplicationInitializer {
}

WebSecurityConfig.java

package com.nhooo;
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("com.nhooo")
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 com.nhooo.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:/";
     }
}

视图

我们有一个JSP文件 index.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 Nhooo! </h4>
<a href="<c:url value='/logout' />">Click here to logout</a>
</body>
</html>

项目结构

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

Spring Security登录注销

输出

使用apache tomcat运行时,它将向浏览器生成以下输出。

Spring Security登录注销1

现在,提供要登录的用户凭据。

Spring Security登录注销2

成功登录后显示首页,请参见下文。

Spring Security登录注销3

在这里,我们创建了一个注销链接,可用于注销。让我们检查一下并从应用程序中注销。

Spring Security登录注销4

它重定向回到登录页面。

Spring security性登录注销5

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