본문 바로가기
개발/Security

[SpringBoot] Security 로그인 인증, 인가(4) - AuthProvider

by 코딩하는 흰둥이 2023. 4. 30.
반응형

이전글 https://greed-yb.tistory.com/225

 

[SpringBoot] Security 로그인 인증, 인가(3) - handler

이전글 https://greed-yb.tistory.com/224 [SpringBoot] Security 로그인 인증, 인가(2) - SecurityConfig 이전글 https://greed-yb.tistory.com/223 [SpringBoot] Security 로그인 인증, 인가(1) - 환경설정 Java 17 Maven Spring Boot 3.0.3 Spring

greed-yb.tistory.com

 

 

AuthProvier

Security 에서 가장 중요한 Class 다

package com.example.practice.security.provider;


import com.example.practice.service.user.UserService;
import com.example.practice.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AuthProvider implements AuthenticationProvider {
    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();   // 로그인 Form에 name에 입력한  Id
        String password = (String) authentication.getCredentials(); // 로그인 Form에 name에 입력한 password

        PasswordEncoder passwordEncoder = userService.passwordEncoder();
        UsernamePasswordAuthenticationToken token;
        UserVo userVo = userService.getUserById(username);

        if (userVo != null && passwordEncoder.matches(password, userVo.getPassword())) { // 일치하는 user 정보가 있는지 확인
            List<GrantedAuthority> roles = new ArrayList<>();

            // 권한 부여
            // 임시로 "ROLE_USER" 라는 권한을 주었고 테이블에 권한 컬럼이 있다면 그 값을 넣어주면 된다 예) userVo.getRole()
            roles.add(new SimpleGrantedAuthority("ROLE_USER"));

            // 인증된 user 정보를 token에 담는다
            token = new UsernamePasswordAuthenticationToken(userVo.getId(), null, roles);

            return token;
        }

        // 문제가 생겼을때 Exception을 반환하지 않으면 정상적으로 실행된 것으로 인식한다
        throw new BadCredentialsException("잘못된 정보입니다.");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}

login Page에서 로그인 요청 시

AuthenticationProvider 로 요청이 전달되어 form입력한 데이터를 처리한다

 

제일 기본적인 메서드만 구현해 놓았으며 현재 소스에서는 권한을 따로 계획하지 않아서

테스트겸 임시로 "ROLE_USER" 이라는 권한을 넣어놨으며 

WebSecurityConfig 에서 "USER" 와 "ADMIN" 이라는 권한 페이지를 따로 두어 제대로 동작하는지 확인하였다

 

DB에서 유저 정보를 가져올 때 권한 정보가 없거나 권한을 이용할 일이 없다면

위의 소스처럼 임의의 role 권한을 넣어주고 WebSecurityConfig 에서 임의의 권한으로 권한체크를 해주면 된다

(물론 login을 한다는 가정하에 - login이 필요없다면 security를 사용할 이유가 사라진다)

댓글