본문 바로가기
Spring

Spring Security Architecture 이해하기

by 슈슈슉민 2024. 6. 10.

번호에 맞게 설명 할 것이다.

 

1. HttpRequest 를 보내면 Dispatcher Servlet 에 도착하기전에 filter가 낚아챈다.

request의 종류에 따라 BasicAuthenticationFilter, UsernamePasswordAuthenticationFilter 등의 다른 종류의 Authentication Filter가 작동한다.

 이 때 AuthenticationFilter에게 올바른 id와 password가 간다면 Authentication 객체를 만든다. 그런다음 UsernamePasswordAuthenticationToken이 만들어진다. 

 

4. Authentication Manager 은 input으로 Authentication object 갖고 인증 완료후에 다시 Authentication object를 반환한다.

 

5. ProviderManagerAuthenticationProviders를 list 형태로 가지고 있다. 인증 메서드에서 적절한 AuthenticateProvider의 인증 메서드를 호출한다. 이에 대한 응답으로 인증이 성공하면 Principal Authentication Object를 가져온다.

 

6. UserDetails 서비스를 사용하여 AuthenticationProvider는 사용자 이름에 해당하는 UserObject를 가져온다. UserObject 자격 증명이 들어오는 AuthenticationObject 자격 증명과 비교된다. Authentication이 성공하면 Principal AuthenticationObject가 응답으로 반환된다. UserDetailsService는 loadUserByUsername이라는 이름의 단일 메서드를 가진 인터페이스이다. CachingUserDetailsService, JDBCDaoImpl 등이 있으며 구현에 따라 적절한 UserDetailsService가 호출된다.

 

spring boot 에 적용하면서

 

기본 보안은 스프링 자동 구성으로 인해 디폴트로 스프링 보안으로 활성화된다. 

 

아래의 custom UserDetails 서비스에서는 WebSecurityConfigureAdapter가 PasswordEncoder를 사용할 것이다.

package com.javainuse.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration  extends WebSecurityConfigurerAdapter{
	
	@Autowired
	CustomUserDetailsService userDetailsService;
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception
	{
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}
	
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		// We don't need CSRF for this example
		httpSecurity.csrf().disable()
				.authorizeRequests().antMatchers("/helloadmin")
				.hasRole("ADMIN")
				.antMatchers("/hellouser")
				.hasAnyRole("ADMIN","USER")
				.and().httpBasic();
	}

}

 

 

package com.javainuse.springsecurity.config;

import java.util.Arrays;
import java.util.List;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		List<SimpleGrantedAuthority> roles=null;
		if(username.equals("admin"))
		{
		roles = Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return new User("admin", "$2y$12$I0Di/vfUL6nqwVbrvItFVOXA1L9OW9kLwe.1qDPhFzIJBpWl76PAe",
					roles);
		}
		else if(username.equals("user"))
		{
		roles = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
		return new User("user", "$2y$12$VfZTUu/Yl5v7dAmfuxWU8uRfBKExHBWT1Iqi.s33727NoxHrbZ/h2",
					roles);
		}
		throw new UsernameNotFoundException("User not found with username: " + username);
	}

}

 


reference [https://www.javainuse.com/webseries/spring-security-jwt/chap3]

 

Understand Spring Security Architecture and implement Spring Boot Security | JavaInUse

 

www.javainuse.com

 

'Spring' 카테고리의 다른 글

Spring Security와 JWT  (0) 2024.06.10
Spring Boot 와 Oauth2 구축  (2) 2024.06.10
[토비의 스프링] 스프링의 이해와 원리  (1) 2024.03.23
static 과 Bean  (0) 2024.02.15