application.properties
spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/[Database name]
spring.datasource.username=[DB user name]
spring.datasource.password=[password]
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
create table USER_TABLE (
USER_ID VARCHAR2(30 char)
, FAMILY_NAME VARCHAR2(10 char) not null
, FIRST_NAME VARCHAR2(10 char) not null
, PASSWORD VARCHAR2(255) not null
, constraint USER_TABLE_PKC primary key (USER_ID)
) ;
The password below is a hash of "pass". I referred to this article.
INSERT INTO
USER_TABLE
VALUES(
'0001'
,'test'
,'Taro'
,'$2a$10$w0C4tFU.SLFATC1Y6Y4uy.vMYsLXhlfvgnFP4dLbRjEa6/Ag1csKS'
);
UserTable.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "USER_TABLE")
public class UserTable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private String userId;
@Column(name = "FAMILY_NAME")
private String familyName;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "PASSWORD")
private String password;
// Getter,Setter omitted
UserTableRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.azkz.entity.UserTable;
@Repository
public interface UserTableRepository extends JpaRepository<UserTable, String> {
public UserTable findByUserId(String userId);
}
DemoSecurityConfig.java
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
//Method to limit the accessible URL and specify the transition destination when login is successful
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.mvcMatchers("/").permitAll() // 「/Can be accessed by anyone
.anyRequest().authenticated() //Otherwise you need to log in
.and()
.formLogin()
.defaultSuccessUrl("/success"); //When login is successful, "/Make a Get request to "success"
}
//Method to hash the entered password with BCrypt method
@Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
DemoUserDetailsService.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 com.azkz.entity.UserTable;
import com.azkz.repository.UserTableRepository;
@Service
public class DemoUserDetailsService implements UserDetailsService {
@Autowired
UserTableRepository userTableRepository;
@Override
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
//Get data from DB based on the entered UserID
UserTable userTable = userTableRepository.findByUserId(userId);
//Input values (user ID, password) and instantiated DemoUserDetails class
//Login check is performed by comparing inside Spring Security.
return new DemoUserDetails(userTable);
}
}
DemoUserDetails.java
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import com.azkz.entity.UserTable;
public class DemoUserDetails extends User {
@Autowired
UserTable userTable;
public DemoUserDetails(UserTable userTable) {
// 「Collections.emptySet()Is originally a collection of authority names. This time it's empty.
super(userTable.getUserId(), userTable.getPassword(),Collections.emptySet());
this.userTable = userTable;
}
//Getter to get unique items from session information
public String getFirstName() {
return this.userTable.getFirstName();
}
public String getFamilyName() {
return this.userTable.getFamilyName();
}
}
DemoController.java
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.azkz.security.DemoUserDetails;
@RestController
public class DemoController {
@GetMapping("/success")
public DemoUserDetails loginSuccess() {
//Get logged-in user information
DemoUserDetails demoUserDetails =
(DemoUserDetails) SecurityContextHolder
.getContext().getAuthentication().getPrincipal();
return demoUserDetails;
}
}
Recommended Posts