SpringBootでの認証情報取得方法

SecurityConfig.java

セキュリティ周りの設定について記載したファイル



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Autowired
    private DataSource dataSource;

    // ログイン後は/homeに遷移させる
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers(header -> {
            header.frameOptions().disable();
        });
        http.authorizeHttpRequests(authz -> authz
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .mvcMatchers("/").permitAll()
            .mvcMatchers("/general").hasRole("GENERAL")
            .mvcMatchers("/admin").hasRole("ADMIN")
            .anyRequest().authenticated()
        );
        http.formLogin(form -> form
    		.loginProcessingUrl("/login")
        	.loginPage("/login")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?error")
            .permitAll()
        );
        http.logout(logout -> logout
        	.logoutUrl("/logout")
        	.logoutSuccessUrl("/login")
        );
        return http.build();
    }
}

LoginUser.java

ログインユーザーの情報を取り出すためのモデル

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Data;

@Data
public class LoginUser implements UserDetails {
	private int id;
	private String user;
	private String password;
	private String familyName;
	private String firstName;
	private Collection<GrantedAuthority> authorities;

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		if (authorities != null) {
			return authorities;
		}

		String role = "GENERAL";
		GrantedAuthority authority = new SimpleGrantedAuthority(role);
		authorities = new ArrayList<>();
		authorities.add(authority);
		return authorities;
	}

	@Override
	public String getUsername() {
		return user;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public String getFullName() {
		return familyName + firstName;
	}

}

UserService.java

サービス(Mapperと接続するためのサービス)を作っておいて、あとからこのサービスを利用して現在のログインユーザー情報を取得する

import java.util.List;

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

import test.spring.exercise.model.LoginUser;
import test.spring.exercise.model.Users;

public interface UsersService {
	public List<Users> selectMany();
	public LoginUser getLoginUser(String username);
}

UserServiceImple.java

サービスクラスの実装

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import test.spring.exercise.model.LoginUser;
import test.spring.exercise.model.Users;
import test.spring.exercise.service.UsersService;
import test.spring.exercise.service.repository.UsersMapper;

@Service
public class UsersServiceImpl implements UsersService{
	@Autowired
	private UsersMapper mapper;

	@Override
	public List<Users> selectMany() {
		// TODO 自動生成されたメソッド・スタブ
		List<Users> users = mapper.selectMany();
		return users;
	}

	@Override
	public LoginUser getLoginUser(String username) {
		return mapper.findOne(username);
	}
}

UserDetailsSevicelImpl.java

実装されたサービスクラスを使用して認証メソッドを拡張する

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import test.spring.exercise.model.LoginUser;
import test.spring.exercise.service.UsersService;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UsersService service;

	@Override
	public UserDetails loadUserByUsername(String username){
		LoginUser loginUser = service.getLoginUser(username);
		return loginUser;
	}

}

UserMapper.java

SQLの実行を定義しているマッパー

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import test.spring.exercise.model.LoginUser;
import test.spring.exercise.model.Users;

@Mapper
public interface UsersMapper {
	/** ユーザー登録 */
	public List<Users> selectMany();

	public LoginUser findOne(String username);
}

UsersMapper.xml

SQL文の定義とマッピング先のメソッドの定義

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- Mapperとxmlのマッピング -->
<mapper namespace="test.spring.exercise.service.repository.UsersMapper">
	<!-- ユーザー全取得 -->
	<select id="selectMany" resultType="Users">
		select
			id,user,family_name,first_name
		from
			user
	</select>
	<select id="findOne" resultType="LoginUser">
		select
			id,pass as password,user,family_name,first_name
		from
			user
		where
			user = #{name}
	</select>
</mapper>

LoginController.java

@PostMapping("/register")
public String postInput(Model model, Locale locale,
		@ModelAttribute @Validated InputForm form, BindingResult bindingResult,
		@AuthenticationPrincipal UserDetails user,
		@RequestParam("register")Boolean register) {

上記の設定によって、画面上からユーザーの情報を取得することができるようになります。

この記事が気に入ったらサポートをしてみませんか?