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

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.w3codebox</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.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

package com.w3codebox;
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.w3codebox)
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.w3codebox.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 전환//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>홈</title>
</head>
<body>
<h3> ${pageContext.request.userPrincipal.name}님, 안녕하세요 </h3>
<h4>환영합니다 w3codebox! </h4>
<a href="<c:url value='/logout' />여기 클릭하여 로그아웃</a>
</body>
</html>

프로젝트 구조

위의 파일을 생성한 후, 프로젝트 구조는 다음과 같습니다:

출력

Apache Tomcat에서 실행할 때, 브라우저에 다음과 같은 출력이 생성됩니다.

로그인할 사용자 인증 정보를 제공하세요.

성공적으로 로그인한 후 홈페이지가 표시됩니다. 아래를 참조하세요.

로그아웃할 수 있는 링크를 여기서 생성했습니다. 확인하고 애플리케이션에서 로그아웃하겠습니다.

로그인 페이지로 리디렉션됩니다.

Spring Security를 통해 로그인 및 로그아웃 기능을 구현하여 Spring MVC 애플리케이션을 성공적으로 생성했습니다.