0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Securityの基本を試す

Posted at

Spring Securityを勉強していたのですが、
公式のドキュメントが難しく"とりあえずログインして認証が必要なページを表示できる"という
動作を成功させるのに苦労したので備忘録を残します。

これで基本的な認証ができます。
公式のドキュメンのサンプルコードを参考にしています。
そのままコピーしてもエラーが出たので、エラーが出ずきちんと動作するように変更しています。

SecurityConfig.java
package com.packt.spring_auth_phot_blog;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import org.springframework.security.core.userdetails.User;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.formLogin(login -> login //  フォーム認証を使う
        .permitAll()) //  フォーム認証画面は認証不要
        .authorizeHttpRequests(authz -> authz
            .requestMatchers("/demo/welcome").permitAll() //  トップページは認証不要
            .anyRequest().authenticated() //  他のURLはログイン後アクセス可能
        );

		return http.build();
	}



	@Bean
	public AuthenticationManager authenticationManager(
			UserDetailsService userDetailsService,
			PasswordEncoder passwordEncoder) {
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(userDetailsService);
		authenticationProvider.setPasswordEncoder(passwordEncoder);

		return new ProviderManager(authenticationProvider);
	}

	@Bean
	public UserDetailsService userDetailsService() {

        UserDetails userDetails = User.withUsername("user")
            .password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG")//passwordは"password"
            .roles("USER")
            .build();

		return new InMemoryUserDetailsManager(userDetails);
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}
}

アクセス制御

ここでアクセス制限をしています。
requestMatchersの引数に指定したパスはpermitAll()により認証していなくても
アクセスできます。逆に、ここで指定していないパスは認証が必要となります。

.requestMatchers("/demo/welcome").permitAll() //  トップページは認証不要

ログインユーザー

ここでログインするユーザーの設定を行なっています。
今回はテストなので固定のユーザーネームとパスワードでログインする仕様になっています。
ユーザー名を"user"、パスワードを"password"でログインします。

	@Bean
	public UserDetailsService userDetailsService() {

        UserDetails userDetails = User.withUsername("user")
            .password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG")//passwordは"password"
            .roles("USER")
            .build();

		return new InMemoryUserDetailsManager(userDetails);
	}

簡単ですが以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?