기본 콘텐츠로 건너뛰기

[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"

댓글

이 블로그의 인기 게시물

[Android] Fragment 위에 Dialog 띄우기

배경:  - Fragment에 Google Maps를 올려 사용자에게 보여주고 있다.  - 사용자가 Dialog 창을 열어 검색을 할 수 있게 하고 싶다. 1. Dialog layout xml 생성 Dialog 창에는 하나의 EditText를 추가하여 사용자로 하여금 String을 입력받게 한다. 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 < LinearLayout   xmlns:android = "http://schemas.android.com/apk/res/android"         android:orientation = "vertical"         android:layout_width = "wrap_content"         android:layout_height = "wrap_content" >     < LinearLayout                 android:orientation = "horizontal"                 android:layout_width = "match_parent"                 android:layout_height = "wrap_content" >         < TextView                         android:layout_width = "match_parent"                         android:layout_height = "match_parent&quo

[Android] Fragment에 RecyclerView 추가하기

배경:  - List View를 보여주는 Fragment로 전환 RecyclerView  위젯은  ListView 의 업그레이드 버전으로 데이터 양이 많은 경우 스크롤을 효율적으로 수행할 수 있는 위젯이다. refer: http://developer.android.com/intl/ko/training/material/lists-cards.html 위 그림과 같이 Adapter를 통해 데이터에 접근하며,  LayoutManager를 통해 위젯 내부 항목들을 배치한다. 따라서 RecyclerView를 적용하기 위해서는     - LayoutManager     - Adaper 를 지정해주어야 한다. 1. 리스트에 보여질 각 항목 item layout 생성 다음과 같이 "id contents" 로 구성하였다. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < ?xml version = "1.0"  encoding = "utf-8" ? > < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"     android:layout_width = "wrap_content"     android:layout_height = "wrap_content"     android:orientation = "horizontal" >      < TextView         android:id = "@+id/id"         android:layout_width = "wrap_content&

미니 메추리 키우기 - 사육장 만들기

미니 메추리는 우리가 알고 있는 일반 메추리보다 조금 작은 개체입니다. 버튼퀼(버튼퀘일)이라고도 불리죠. 일반 메추리보다 작기도 하고 짝이 맞는 암수가 같이 있으면 그리 시끄럽지도 않습니다. 여러 모로 키우기가 좀더 수월하죠. 첫 번째 단계로 먼저 아이들이 지낼 집을 만들어 주었습니다. 사실 여러 고민을 많이 했어요 지금 소개하는 집을 만들기 전에는 120L 짜리 대형 리빙 박스로 집을 만들어 주었었죠. 값이 저렴하고 개량하는 것이 크게 어렵지 않기 때문에 많은 분들이 리빙 박스를 개조하여 집을 만들어 주고 있어요. 저 같은 경우는 보온을 생각해서 안쪽에는 단열재를 덧대기도 했죠. 하지만 사실 리빙 박스로 집을 만드는게 아주 쉽지만은 않아요. 물론 있는 그대로를 사용하신다면 어려울 건 전혀 없죠. 그런데 만약 전구를 달기 위해 구멍을 뚫거나, 환기 구멍을 뚫거나 기타 여러 필요에 의해 리빙 박스를 뜯어 고쳐야 한다면 이야기가 달라지죠. 저도 사실 이런 불편함에 고민고민을 하다가 오늘 소개해 드릴 두 번째 집과 같은 것을 생각하게 되었어요. 바로 시중에서 쉽게 구할 수 있는 종이 박스를 활용한 것인데요. 위쪽 뚜껑에는 구멍을 두 개를 뚫었어요. 작은 구멍은 온도 조절을 위한 전구 바로 위쪽으로 온도가 너무 올라갈 경우 온도 조절을 위해 뚫어 놓았고요.  아래 좀더 큰 구멍은 물, 먹이 등을 교체해주기 위한 구멍이에요.  정면에는 창을 내어 관찰할 수 있게 했어요. 지금은 저 가운데도 잘라내서 크게 창 하나로 만들었어요. 안쪽에는 온도계를 비치하여 내부 온도를 확인할 수 있게 해두었습니다. (지금 생각해보니 전구 바로 아래쪽에 위치한 탓에 제대로 된 온도 측정이 될지 모르겠네요;;;) 그리고 보셔서 아시겠지만, 내부 바닥, 옆면에 단