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

[장준희] 프리코스 미션 제출합니다. #8

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,25 @@ plugins {

group = 'nextstep'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
sourceCompatibility = "16"

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'

// lombok
compileOnly "org.projectlombok:lombok"
testCompileOnly "org.projectlombok:lombok"
annotationProcessor "org.projectlombok:lombok"
testAnnotationProcessor "org.projectlombok:lombok"

testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
useJUnitPlatform()
}
targetCompatibility = JavaVersion.VERSION_16
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package nextstep.app.application;

import nextstep.app.domain.MemberRepository;
import nextstep.security.userdetils.UserDetails;
import nextstep.security.userdetils.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

private final MemberRepository memberRepository;

public CustomUserDetailsService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}

@Override
public UserDetails loadUserByUsername(String username) {
return memberRepository.findByEmail(username)
.map(member -> new UserDetails() {

@Override
public String getUsername() {
return member.getEmail();
}

@Override
public String getPassword() {
return member.getPassword();
}
}).orElse(null);
}
}
1 change: 1 addition & 0 deletions src/main/java/nextstep/app/domain/MemberRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Optional;

public interface MemberRepository {

Optional<Member> findByEmail(String email);

List<Member> findAll();
Expand Down
32 changes: 0 additions & 32 deletions src/main/java/nextstep/app/ui/LoginController.java

This file was deleted.

6 changes: 6 additions & 0 deletions src/main/java/nextstep/app/ui/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -23,4 +25,8 @@ public ResponseEntity<List<Member>> list() {
return ResponseEntity.ok(members);
}

@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<Void> handleAuthenticationException() {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
60 changes: 60 additions & 0 deletions src/main/java/nextstep/app/ui/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package nextstep.app.ui;

import java.util.Collections;
import java.util.List;
import lombok.RequiredArgsConstructor;
import nextstep.security.SecurityContextHolderFilter;
import nextstep.security.authentication.AuthenticationManager;
import nextstep.security.authentication.DaoAuthenticationProvider;
import nextstep.security.authentication.ProviderManager;
import nextstep.security.filter.BasicAuthenticationSecurityFilter;
import nextstep.security.filter.DefaultSecurityFilterChain;
import nextstep.security.filter.DelegatingFilterProxy;
import nextstep.security.filter.FilterChainProxy;
import nextstep.security.filter.FormLoginAuthenticationFilter;
import nextstep.security.filter.SecurityFilterChain;
import nextstep.security.userdetils.UserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {

private final UserDetailsService userDetailsService;

@Bean
public DelegatingFilterProxy delegatingFilterProxy(
AuthenticationManager authenticationManager
) {
return new DelegatingFilterProxy(
filterChainProxy(List.of(securityFilterChain(authenticationManager))
));
}

@Bean
public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChainList) {
return new FilterChainProxy(securityFilterChainList);
}

@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(daoAuthenticationProvider()));
}

@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
return new DaoAuthenticationProvider(userDetailsService);
}

@Bean
public SecurityFilterChain securityFilterChain(AuthenticationManager authenticationManager) {
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new FormLoginAuthenticationFilter(authenticationManager),
new BasicAuthenticationSecurityFilter(authenticationManager))
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package nextstep.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class HttpSessionSecurityContextRepository {

private final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";

public SecurityContext loadContext(HttpServletRequest request) {
HttpSession session = request.getSession(false);

if (session == null) {
return null;
}

return (SecurityContext) session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
}

private void saveContext(
SecurityContext context,
HttpServletRequest request,
HttpServletResponse response
) {
HttpSession session = request.getSession();
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, context);
}
}
18 changes: 18 additions & 0 deletions src/main/java/nextstep/security/SecurityContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package nextstep.security;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import nextstep.security.authentication.Authentication;

@Setter
@Getter
@NoArgsConstructor
public class SecurityContext {

private Authentication authentication;

public SecurityContext(Authentication authentication) {
this.authentication = authentication;
}
}
35 changes: 35 additions & 0 deletions src/main/java/nextstep/security/SecurityContextHolder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package nextstep.security;

public class SecurityContextHolder {

private static final ThreadLocal<SecurityContext> contextHolder;

static {
contextHolder = new ThreadLocal<>();
}

public static void clearContext() {
contextHolder.remove();
}

public static SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();

if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}

return ctx;
}

public static void setContext(SecurityContext context){
if (context != null){
contextHolder.set(context);
}
}

public static SecurityContext createEmptyContext() {
return new SecurityContext();
}
}
25 changes: 25 additions & 0 deletions src/main/java/nextstep/security/SecurityContextHolderFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package nextstep.security;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.filter.GenericFilterBean;

public class SecurityContextHolderFilter extends GenericFilterBean {

private final HttpSessionSecurityContextRepository sessionSecurityContextRepository = new HttpSessionSecurityContextRepository();

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
SecurityContext context = this.sessionSecurityContextRepository.loadContext((HttpServletRequest) request);
SecurityContextHolder.setContext(context);

chain.doFilter(request, response);

SecurityContextHolder.clearContext();
}
}
10 changes: 10 additions & 0 deletions src/main/java/nextstep/security/authentication/Authentication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package nextstep.security.authentication;

public interface Authentication {

Object getCredentials();

Object getPrincipal();

boolean isAuthenticated();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package nextstep.security.authentication;

public interface AuthenticationManager {

Authentication authenticate(Authentication authentication);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package nextstep.security.authentication;

public interface AuthenticationProvider {

Authentication authenticate(Authentication authentication);

boolean supports(Class<?> authentication);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package nextstep.security.authentication;

import nextstep.app.ui.AuthenticationException;
import nextstep.security.userdetils.UserDetails;
import nextstep.security.userdetils.UserDetailsService;

public class DaoAuthenticationProvider implements AuthenticationProvider {

private final UserDetailsService userDetailsService;

public DaoAuthenticationProvider(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getPrincipal().toString());

if (userDetails == null) {
throw new AuthenticationException();
}

if (!userDetails.getPassword().equals(authentication.getCredentials())) {
throw new AuthenticationException();
}

return UsernamePasswordAuthenticationToken.authenticated(userDetails, userDetails.getPassword());
}

@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package nextstep.security.authentication;

import java.util.List;

public class ProviderManager implements AuthenticationManager {
private List<AuthenticationProvider> providers;

public ProviderManager(List<AuthenticationProvider> providers) {
this.providers = providers;
}

@Override
public Authentication authenticate(Authentication authentication) {
for (AuthenticationProvider provider : providers) {
if (!provider.supports(authentication.getClass())) {
continue;
}
Authentication result = provider.authenticate(authentication);
return result;
}

return null;
}
}
Loading