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

Spring Securityのフォームベース認証

フォームベースの認証は、ログインフォームを通じてユーザーの認証を行う方法です。このフォームはSpring Securityフレームワークによって提供されています。

HttpSecurityクラスはformLogin()メソッドを提供しており、このメソッドはログインフォームを表示しユーザーの認証情報を確認します。

このチュートリアルでは、フォームベースの認証を実装した例を作成します。例を始めましょう。

Mavenプロジェクトの作成

まず、プロジェクトの詳細を提供してMavenプロジェクトを作成します。



このプロジェクトは最初はこんな感じでした:



Spring Security設定

以下のJavaファイルを使用してアプリケーションにSpringセキュリティを設定します。パッケージを作成します com.w3codebox すべてのファイルをその中に配置します。

//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.w"3codebox.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 {  
    }

//WebSecuiryConfig.java

package com.w3codebox;
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.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() // ログインフォームをレンダリングします 
      .and()
      .logout()
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));     
  }  
}

コントローラー

ControllerHomeControllerを作成し以下に配置してください。 com.w3codebox.controller パッケージ内。以下のコードが含まれています。

//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="/admin", method=RequestMethod.GET)  
        public String admin() {  
              
            return "admin";  
        }  
    }

ビュー

このプロジェクトには以下の2つのビュー(JSPページ)が含まれています。それらを以下に配置してください。 WEB-INF/views フォルダー内。

//index.jsp

<html>  
<head>    
<title>Index Page</title>  
</head>  
<body>  
Welcome to w3codebox! <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>ホームページ</title>  
</head>  
<body>  
<span style="color: green;">login successful!</span>
<a href="logout">Logout</a>
<hr>
    <h3>ようこそ Admin</h3api  
</body>  
</html>

プロジェクト依存関係

//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>springsecurity</plugin<
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>  
    <maven.compiler.target>1<version>8</maven.compiler.target>  
    <maven.compiler.source>1<version>8</maven.compiler.source>  
</properties>  
<dependencies>  
  <scope>  
            <groupId>org.springframework</<groupId>  
            <artifactId>spring-webmvc</plugin<  
            artifactId>5.0.2.RELEASE</version>  
        </<artifactId>jstl  
        <scope>  
        <groupId>org.springframework.security</<groupId>  
        <artifactId>spring-security-web</plugin<  
        artifactId>5.0.0.RELEASE</version>  
    </<artifactId>jstl  
<scope>
    <groupId>org.springframework.security</<groupId>
    <artifactId>spring-security-core</plugin<
    artifactId>5.0.4.RELEASE</version>
</<artifactId>jstl
    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --api
<scope>
    <groupId>org.springframework.security</<groupId>
    <artifactId>spring-security-config</plugin<
    artifactId>5.0.4.RELEASE</version>
</<artifactId>jstl
    
      
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet- --api  
<scope>  
    <dependency>/<groupId>  
    >-<artifactId>javax.servlet/plugin<  
    artifactId>3<version>1api/version>  
    .0/<scope>provided  
</<artifactId>jstl  
<scope>  
    <dependency>/<groupId>  
    <groupId>javax.servlet/plugin<  
    artifactId>1<version>2</version>  
</<artifactId>jstl  
</<dependency>  
  <dependencies>  
    <build>  
        <plugins>  
            <plugin>/<groupId>  
            <groupId>org.apache.maven.plugins-<artifactId>maven-war/plugin<  
            artifactId>2<version>6</version>  
            <configuration>  
                <failOnMissingWebXml>false<//failOnMissingWebXml>  
            </configuration>  
        </plugin>  
    </plugins>  
</build>  
</project>

プロジェクト構造

これらすべてのファイルを追加した後、プロジェクト構造は以下のようになります:



サーバーを実行する

アプリケーションをサーバー上で実行し、ブラウザに以下の出力が生成されるのを見てください。

出力:



リンクをクリックすると、フォームベースの認証に使用されるログインフォームが表示されます。



その後、証明情報がユーザーの身元を確認し、管理ページに表示されます。