お世話になります。
Spring BootとSpring Securityを使用して、ログイン認証を実装しています。
デフォルトでは、DBにusernameとpasswordのカラムを持っていないといけないと思うのですが、
usernameをlogin_idというカラムで持ちたいと思っています。
実装方法を調べたのですが、ログイン認証の実装方法が自分と違っていたので、
参考にはなりませんでした。
ご教示頂けますと幸いです。
現時点のデフォルトのまま実装しているソースコードを記載致します。
//LoginController.java package com.sample; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { public static final String PAGE = "/login"; private static final String HTML = "login"; @RequestMapping(value = LoginController.PAGE) public String top(Model model) { return LoginController.HTML; } }
//TopController.java package com.sample; import java.security.Principal; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class TopController { public static final String PAGE = "/"; private static final String HTML = "top"; @RequestMapping(value = TopController.PAGE, method = RequestMethod.GET) public String top(Principal principal, Model model) { Authentication authentication = (Authentication) principal; MemberEntity user = (MemberEntity) authentication.getPrincipal(); model.addAttribute("user", user); return TopController.HTML; } }
//MemberEntity.java package com.sample; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @Entity @Table(name = "member") public class MemberEntity implements UserDetails { private static final long serialVersionUID = 1667698003975566301L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
//MemberRepository.java package com.sample; import org.springframework.data.jpa.repository.JpaRepository; public interface MemberRepository extends JpaRepository<MemberEntity, Long> { public MemberEntity findByUsername(String username); }
//MemberServiseImpl.java package com.sample; import org.apache.commons.lang3.StringUtils; 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; @Service public class MemberServiceImpl implements UserDetailsService { private MemberRepository memberRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if (StringUtils.isEmpty(username)) { throw new UsernameNotFoundException(""); } MemberEntity memberEntity = memberRepository.findByUsername(username); if (memberEntity == null) { throw new UsernameNotFoundException(""); } return memberEntity; } @Autowired public void setMemberRepository(MemberRepository memberRepository) { this.memberRepository = memberRepository; } }
//WebSecurityConfig.java package com.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests().anyRequest().authenticated(); httpSecurity.formLogin().loginPage(LoginController.PAGE).usernameParameter("user") .passwordParameter("pass").permitAll(); httpSecurity.logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout**")) // ログアウト処理のパス .logoutSuccessUrl("/login"); } @Override protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(this.userDetailsService) .passwordEncoder(NoOpPasswordEncoder.getInstance());; } @Autowired public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } }
//Login.html <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>ログイン</title> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> </head> <body> <form action="" th:action="@{/login}" method="post"> <p> ユーザーID: <input type="text" name="user" /> </p> <p> パスワード: <input type="password" name="pass" /> </p> <p> <input type="submit" value="ログイン" /> </p> </form> <div th:if="${session['SPRING_SECURITY_LAST_EXCEPTION']} != null"> <span th:text="${session['SPRING_SECURITY_LAST_EXCEPTION'].message}"></span> </div> </body> </html>
以上となります。宜しくお願い申し上げます。
質問の主旨が良く分かりません。usernameの代わりにlogin_idというカラム名を使うにはどうすればいいですか?ということでしょうか?
unz.hori様 いつもお世話になっております。わかりづらい内容で申し訳ありません。unz.hori様のおっしゃっている意味であっています。現在は、DB内のusernameカラムとpasswordカラムで認証を行っているのですが、usernameカラムをlogin_idというカラム名に変更したいのです。その際に、Spring側ではどこを修正すればいいのかわからず困っています。 ログイン認証は右記のサイトを参考にしています。参考サイト(https://qiita.com/knamae/items/8128c7eaa687296470d7)
丸パクリできるソースは基本ないです
変えたい場所をすでにあなたは変更してますが何がわからないんでしょうか?
asahina1979様 usernameではなくlogin_idというカラム名で認証を行いたいのですが、すでに変更してあるというのはどの箇所でしょうか?
回答3件
あなたの回答
tips
プレビュー