기본 콘텐츠로 건너뛰기

[Spring Security] User Authentication Example - 2. Custom Authentication Provider 구현 및 Login Form 작성

1. AuthenticationProvider 인터페이스 구현

org.springframework.security.authentication.AuthenticationProvider



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class CustomAuthenticationProvider implements AuthenticationProvider {
    
    private UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        String email = (String) auth.getPrincipal();
        String password = (String) auth.getCredentials();
        User user = (User) userService.loadUserByUsername(email);
        
        if (user.getPassword().equals(password)) {
            logger.info("Authentication Success!!! {}", email);
            List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
            roles.add(new SimpleGrantedAuthority("ROLE_USER"));
            UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(email, password, roles);
            result.setDetails(user);
            return result;
        } else {
            logger.warn("Authentication Failed!!! {}", email);
            throw new BadCredentialsException("Bad credentials");
        }
    }
    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
    
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
cs

사용자가 ID/PW 를 입력하고 Login 버튼을 누르면
Spring Security는 CustomAuthenticationProvider의 authenticate() 메서드를 호출한다.
이 메서드에서 실제 인증에 대해 구현해주면 된다.

UserService 빈을 통해 DB에서 해당 ID(email 주소를 id로 사용하였다.)의 사용자 계정이 존재하는지 확인하며
존재하지 않는 경우 Exception을 발생시킨다.



2. Login Form 구현

org.springframework.security.authentication.AuthenticationProvider

1
2
3
4
5
6
7
8
9
10
<form:form commandName="user" action="loginProcess">
    <!-- 1. Email -->
    <form:label path="email">E-Mail</form:label>
    <form:input path="email"></form:input>
 
    <!-- 2. Password -->        
    <form:label path="password">Password</form:label>
    <form:input path="password" type="password"></form:input>
    <form:button type="submit">Log In</form:button>
</form:form>
cs

form의 action은 앞서 security-context.xml의 login-processing-url 값과 동일한 것을 지정한다. 
login-processing-url="/loginProcess"

댓글