Configuration
main application
- WebMvcConfigurerAdapter 를 상속해 아래의 두 메서드를 @Override 했다.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
/**
* Web Security 를 위해 WebMvcConfigurerAdapter를 상속하고 아래 2개의 메서드를 추가하였다.
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login"); //resource 데렉토리 아래에 login.html 존재
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new ReaderHandlerMethodArgumentResolver());
}
}
HandlerMethodArgumentResolver 구현
이 예에서는 Reader 클래스가 UserDetails 를 구현한 타입이므로, HandlerMethodArgumentResolver 인터페이스를 구현하는 ReaderHandlerMethodArgumentResolver 라는 클래스를 선언했다.
package com.example.demo;
import com.example.demo.vo.Reader;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Optional;
public class ReaderHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return Reader.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication auth = (Authentication) webRequest.getUserPrincipal();
// if(Objects.nonNull(auth) && auth.getPrincipal() instanceof Reader)
// return auth.getPrincipal();
// else
// return null;
return Optional.ofNullable(auth)
.map(Authentication::getPrincipal)
.filter(self -> self instanceof Reader)
.orElse(null);
}
}