LoginSignup
8
10

More than 5 years have passed since last update.

SpringSecurityでDBログイン認証処理を実装してみた(MyBatis使用)その2

Last updated at Posted at 2017-10-30

概要

前回の続きです。
今回は、ServiceクラスとSecurityConfigクラスを作ってこうと思います。

手順

Serviceクラスの設定

Serveiceクラスは、SpringSercurityで定義されているUserDetailsServiceインターフェイスをの実装クラスです。

TCustomerService
@Service
public class TCustomerService implements UserDetailsService {

    @Autowired
    private TCustomerMapper tCustomerMapper;//DB接続処理を行うMapperクラスを参照します。

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TCustomer tCustomer = tCustomerMapper.findByUsername(username);
        if(tCustomer == null) {
            throw new UsernameNotFoundException(username + " is not found");
        }
        return new TCustomerUserDetails(tCustomer);
    }
}

SecurityConfigの設定

このクラスは、認証に関する設定を担当し、SpringSecurityで定義されているWebSecurityConfigureAdapterを継承します。
user,pass等の変数は後述する、loginForm.htmlにて定義しています。

WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)//デフォルトConfigの上書き
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //アクセスポリシーの設定
        http.authorizeRequests()
            //指定したパターンごとに制限をかける
            .antMatchers("/js/**", "/css/**").permitAll()//制限なし
            .anyRequest().authenticated();//上記以外は制限あり
        //フォーム認証の設定
        http.formLogin()
            //ログインページの指定(指定なしの場合デフォルトのものが用意される
            .loginPage("/loginForm")
            //ログイン処理のパス
            .loginProcessingUrl("/login")
            //ログインフォームの入力値のname
            .usernameParameter("user")
            .passwordParameter("pass")
            //ログイン成功時に遷移するページ(trueで成功時は常にここに飛ぶ)
            .defaultSuccessUrl("/", true)
            //失敗時の遷移先、アクセス制限は解除する
            .failureUrl("/loginForm?error=true").permitAll();
    }
}

WebSecurityConfigにつきましてはSpringScurity4.0以前では独自の認証方法を設定した、UserDetailsServiceを実装したクラスを明示的に参照する必要がありましたが、4.1以降では、DIコンテナから自動検出するそうです。

今回はここまで、次回はログインフォームと、ログインしたユーザを迎えるかんたんなtopページを作ろうと思います。

参考書籍 Spring徹底入門 Spring FrameworkによるJavaアプリケーション開発
参考サイト 公式doc

8
10
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
8
10