2023-05-15に更新

【Spring Security】ログイン画面を作ってみた

SpringBoot Java 公開下書き

プロジェクトの作成

今回は、STSを使用してプロジェクトを作成していきます。

画像のように、新規プロジェクトを作成します。

image

image

依存関係として、

Lombok
DevTools
Spring Securiy
Spring Web

を導入しました。

コンフィグファイルを作る

遷移先のファイル指定やログイン処理をするコンフィグファイルを作ります。

まずは、遷移先のファイルを指定するMVCコンフィグファイルを作ります。

image

【MVCコンフィグファイル】

package com.example.demo.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// コンフィグクラスであることを示すアノテーション
@Configuration
public class DemoConfig implements WebMvcConfigurer {
    // 遷移先を設定してあげる
    public void addViewControllers(ViewControllerRegistry reg) {
        // 入力されたURLに対して、どのViewを返すかを記述する
        reg.addViewController("/").setViewName("home");
        reg.addViewController("/home").setViewName("home");
        reg.addViewController("/start").setViewName("start");
        reg.addViewController("/login").setViewName("login");
    }
}

【WEBコンフィグファイル】

package com.example.demo.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

// コンフィグクラスであることを示すアノテーション
@Configuration
// Webセキュリティを有効にする
@EnableWebSecurity
public class DemoWebConfig{
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
        .authorizeHttpRequests((requests) -> requests
            .requestMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
        )
        .formLogin((form) -> form
            .loginPage("/login")
            .permitAll()
        )
        .logout((logout) -> logout.permitAll());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}
何度でもクリック!→

HelloWorld

Crieitは個人で開発中です。 興味がある方は是非記事の投稿をお願いします! どんな軽い内容でも嬉しいです。
なぜCrieitを作ろうと思ったか

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください!

ボードとは?

HelloWorld の最近の記事