Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Step2] 리펙터링 #6

Open
wants to merge 9 commits into
base: hyunssooo
Choose a base branch
from
46 changes: 17 additions & 29 deletions src/main/java/nextstep/app/config/AuthConfig.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package nextstep.app.config;

import java.util.List;
import nextstep.security.access.matcher.MvcRequestMatcher;
import nextstep.security.authentication.AuthenticationManager;
import nextstep.security.authentication.BasicAuthenticationFilter;
import nextstep.security.authentication.UsernamePasswordAuthenticationFilter;
import nextstep.security.authentication.UsernamePasswordAuthenticationProvider;
import nextstep.security.authorization.AuthorizationFilter;
import nextstep.security.authorization.RoleManager;
import nextstep.security.authorization.PreAuthorizationFilter;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.AuthorizeRequestMatcherRegistry;
import nextstep.security.config.FilterChainProxy;
import nextstep.security.config.SecurityFilterChain;
import nextstep.security.context.HttpSessionSecurityContextRepository;
Expand All @@ -17,6 +19,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
Expand All @@ -34,48 +37,29 @@ public DelegatingFilterProxy securityFilterChainProxy() {
}

@Bean
public FilterChainProxy filterChainProxy(
SecurityFilterChain loginSecurityFilterChain,
SecurityFilterChain membersSecurityFilterChain
) {
return new FilterChainProxy(
loginSecurityFilterChain,
membersSecurityFilterChain
);
public FilterChainProxy filterChainProxy(SecurityFilterChain securityFilterChain) {
return new FilterChainProxy(securityFilterChain);
}

@Bean
public SecurityFilterChain loginSecurityFilterChain(
public SecurityFilterChain securityFilterChain(
AuthenticationManager authenticationManager,
SecurityContextRepository securityContextRepository
) {
return new DefaultSecurityFilterChain(
new MvcRequestMatcher(
HttpMethod.POST,
"/login"
),
new UsernamePasswordAuthenticationFilter(
authenticationManager,
securityContextRepository
)
);
}

@Bean
public SecurityFilterChain membersSecurityFilterChain(
AuthenticationManager authenticationManager,
SecurityContextRepository securityContextRepository
) {
return new DefaultSecurityFilterChain(
new MvcRequestMatcher(
HttpMethod.GET,
"/members"
),
new BasicAuthenticationFilter(
authenticationManager,
securityContextRepository
),
new AuthorizationFilter(securityContextRepository, new RoleManager("ADMIN"))
new PreAuthorizationFilter(securityContextRepository),
new AuthorizationFilter(
new AuthorizeRequestMatcherRegistry()
.matcher(new MvcRequestMatcher(HttpMethod.GET, "/members")).hasAuthority("ADMIN")
.matcher(new MvcRequestMatcher(HttpMethod.GET, "/members/me")).authenticated()
)
);
}

Expand All @@ -89,4 +73,8 @@ public AuthenticationManager authenticationManager() {
return new AuthenticationManager(new UsernamePasswordAuthenticationProvider(userDetailsService));
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new LoginUserArgumentResolver());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오오 ArgumentResolver 사용 좋네요! 👏👏

}
}
31 changes: 31 additions & 0 deletions src/main/java/nextstep/app/config/LoginUserArgumentResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package nextstep.app.config;

import javax.servlet.http.HttpServletRequest;
import nextstep.app.ui.dto.LoginUser;
import nextstep.security.context.SecurityContext;
import org.springframework.core.MethodParameter;
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;

public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(LoginUser.class);
}

@Override
public LoginUser resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) {
final HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
final SecurityContext context = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
final String email = context.getAuthentication().getPrincipal().toString();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SecurityContextHolder를 사용해서 가져올 수도 있겠네요!

SecurityContextHolder.getContext().getAuthentication();

(+) 조금 더 나아가보면, 지금은 Authentication의 Pricipal로 String(username)을 사용하고 있는데요.
Pricipal로 객체를 리턴할 수도 있어요!

return new LoginUser(email);
}
}
17 changes: 12 additions & 5 deletions src/main/java/nextstep/app/ui/MemberController.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package nextstep.app.ui;

import nextstep.security.authentication.Authentication;
import nextstep.security.context.SecurityContextHolder;
import java.util.List;
import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
import nextstep.app.ui.dto.LoginUser;
import nextstep.security.exception.AuthenticationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/members")
public class MemberController {

private final MemberRepository memberRepository;
Expand All @@ -19,10 +20,16 @@ public MemberController(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}

@GetMapping("/members")
@GetMapping
public ResponseEntity<List<Member>> list() {
List<Member> members = memberRepository.findAll();
return ResponseEntity.ok(members);
}

@GetMapping("/me")
public ResponseEntity<Member> me(LoginUser loginUser) {
final Member member = memberRepository.findByEmail(loginUser.getEmail())
.orElseThrow(() -> new AuthenticationException());
return ResponseEntity.ok(member);
}
}
20 changes: 20 additions & 0 deletions src/main/java/nextstep/app/ui/dto/LoginUser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package nextstep.app.ui.dto;

public class LoginUser {
private final String email;

public LoginUser(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

@Override
public String toString() {
return "LoginUser{" +
"email='" + email + '\'' +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public boolean matches(HttpServletRequest request) {
return false;
}

return request.getRequestURI().contains(pattern);
return request.getRequestURI().equals(pattern);
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
package nextstep.security.authorization;

import java.io.IOException;
import java.util.Optional;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nextstep.security.context.SecurityContext;
import nextstep.security.context.SecurityContextRepository;
import nextstep.security.authentication.Authentication;
import nextstep.security.authorization.manager.RoleManager;
import nextstep.security.config.AuthorizeRequestMatcherRegistry;
import nextstep.security.context.SecurityContextHolder;
import nextstep.security.exception.AccessDeniedException;
import nextstep.security.exception.AuthenticationException;
import nextstep.security.exception.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.GenericFilterBean;

public class AuthorizationFilter extends GenericFilterBean {

private final SecurityContextRepository securityContextRepository;
private final RoleManager roleManager;
private final AuthorizeRequestMatcherRegistry authorizeRequestMatcherRegistry;

public AuthorizationFilter(SecurityContextRepository securityContextRepository, RoleManager roleManager) {
this.securityContextRepository = securityContextRepository;
this.roleManager = roleManager;
public AuthorizationFilter(AuthorizeRequestMatcherRegistry authorizeRequestMatcherRegistry) {
this.authorizeRequestMatcherRegistry = authorizeRequestMatcherRegistry;
}

@Override
Expand All @@ -30,12 +33,40 @@ public void doFilter(
FilterChain chain
) throws IOException, ServletException {
try {
final SecurityContext context = securityContextRepository.loadContext((HttpServletRequest) request);
if (context.getAuthentication().getAuthorities().stream().noneMatch(roleManager::hasRole)) {
final Authentication authentication = Optional.ofNullable(
SecurityContextHolder
.getContext()
.getAuthentication()
).orElseThrow(AuthenticationException::new);

final RoleManager roleManager = authorizeRequestMatcherRegistry.getRoleManager((HttpServletRequest) request);

if (roleManager == null) {
chain.doFilter(request, response);
return;
}


if (!roleManager.check(authentication)) {
throw new AuthorizationException();
}
} catch (AuthenticationException e) {
((HttpServletResponse) response).sendError(
HttpStatus.UNAUTHORIZED.value(),
HttpStatus.UNAUTHORIZED.getReasonPhrase()
);
return;
} catch (AuthorizationException e) {
((HttpServletResponse) response).sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
((HttpServletResponse) response).sendError(
HttpStatus.FORBIDDEN.value(),
HttpStatus.FORBIDDEN.getReasonPhrase()
);
return;
} catch (AccessDeniedException e) {
((HttpServletResponse) response).sendError(
HttpStatus.BAD_REQUEST.value(),
HttpStatus.BAD_REQUEST.getReasonPhrase()
);
return;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package nextstep.security.authorization;

import java.io.IOException;
import java.util.Optional;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import nextstep.security.authentication.Authentication;
import nextstep.security.context.SecurityContext;
import nextstep.security.context.SecurityContextHolder;
import nextstep.security.context.SecurityContextRepository;
import org.springframework.web.filter.GenericFilterBean;

public class PreAuthorizationFilter extends GenericFilterBean {

private final SecurityContextRepository securityContextRepository;

public PreAuthorizationFilter(SecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
}

@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
try {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
chain.doFilter(request, response);
return;
}

final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
SecurityContext context = Optional.ofNullable(
(SecurityContext) httpServletRequest.getSession()
.getAttribute(SecurityContextHolder.SPRING_SECURITY_CONTEXT_KEY)
)
.orElseGet(() -> securityContextRepository.loadContext(httpServletRequest));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주입된 securityContextRepository가 HttpSessionSecurityContextRepository 인데 동일한 일을 하고 있지 않나요?


final Authentication authentication = Optional.ofNullable(context)
.map(it -> it.getAuthentication())
.orElse(null);

SecurityContextHolder.getContext().setAuthentication(authentication);

} catch (Exception ignored) {

}
chain.doFilter(request, response);
}
}
20 changes: 0 additions & 20 deletions src/main/java/nextstep/security/authorization/RoleManager.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package nextstep.security.authorization.manager;

import nextstep.security.authentication.Authentication;

public class AuthenticationRoleManager implements RoleManager {

@Override
public boolean check(Authentication authentication) {
return authentication.isAuthenticated();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package nextstep.security.authorization.manager;

import java.util.Set;
import nextstep.security.authentication.Authentication;

public class AuthorizationRoleManager implements RoleManager {

private final Set<String> authorities;

public AuthorizationRoleManager(Set<String> authorities) {
this.authorities = authorities;
}

public AuthorizationRoleManager(String... authorities) {
this(Set.of(authorities));
}

@Override
public boolean check(Authentication authentication) {
return authentication.getAuthorities().stream()
.anyMatch(authorities::contains);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package nextstep.security.authorization.manager;

import nextstep.security.authentication.Authentication;

public class DenyAllRoleManager implements RoleManager {

@Override
public boolean check(Authentication authentication) {
return false;
}
}
Loading