1. BasicAuthenticationFilter
- 기본적인 로그인 페이지(formLogin)을 사용 할 수 없을 때 사용
- SPA(Single Page Application) 페이지 같은 뷰를 프론트 단에서 책임지는 방식의 브라우저 기반의 모바일 앱에 사용
- http 헤더값으로 전달 되기 때문에 httpBasic()를 허용하여 BasicAuthenticationFilter 사용, 헤더 값이 base64인코딩 되어 전달 되기 때문에 보안에 매우 취약하여 반드시 https 프로토콜 사용을 권장.
- 최초의 로그인 시에만 인증을 처리하고, 이후에 session에 의존
- 에러 시 401인 UnAuthorized 발생
@Configuration
public class MobSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserManager userManager;
private final AdminManager adminManager;
public MobSecurityConfig(UserManager userManager, AdminManager adminManager) {
this.userManager = userManager;
this.adminManager = adminManager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
* AuthenticationManagerBuilder 의 authenticationProvider()
* 는 List로 쌓아놓고 사용
*/
auth.authenticationProvider(userManager);
auth.authenticationProvider(adminManager);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
/**
* BasicAuthenticationFilter Test
*/
http
.antMatcher("/rest/**")
.csrf().disable()
.authorizeRequests(request->request.anyRequest().authenticated()) //permitAll()
.httpBasic()
;
}
}
BasicAuthenticationFilter 토큰 인증 방식
- SecurityContext에 인증된 토큰이 없다면 위와 같은 포맷의 토큰을 받아 인증 처리
샘플 코드
Controller
@RestController
@RequestMapping("/rest")
public class BasicAuthController {
@Autowired
private UserManager userManager;
@GetMapping("/greeting")
public String greeting(){
return "hello";
}
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
@GetMapping("/user/list")
public List<User> studentList(@AuthenticationPrincipal Admin admin, Model model){
return userManager.myUserList(admin.getId());
}
}
SecurityConfig
@Configuration
public class MobSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserManager userManager;
private final AdminManager adminManager;
public MobSecurityConfig(UserManager userManager, AdminManager adminManager) {
this.userManager = userManager;
this.adminManager = adminManager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(User.builder()
.username("user")
.password("1111")
.roles("USER")
)
;
/**
* AuthenticationManagerBuilder 의 authenticationProvider()
* 는 List로 쌓아놓고 사용
*/
auth.authenticationProvider(userManager);
auth.authenticationProvider(adminManager);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
/**
* BasicAuthenticationFilter Test
*/
http
.antMatcher("/rest/**")
.csrf().disable()
.authorizeRequests(request->request.anyRequest().authenticated()) //permitAll()
.httpBasic()
;
}
}
Test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BasicAuthenticationTest {
@LocalServerPort
int port;
RestTemplate client = new RestTemplate();
TestRestTemplate client1 = new TestRestTemplate("v", "1");
private String greetingUrl(){
return "http://localhost:"+port+"/rest/greeting";
}
@Test
void test1_basicFail(){
/**
* Error 발생하여 401 확인
*/
HttpClientErrorException exception = assertThrows(HttpClientErrorException.class, ()->{
client.getForObject(greetingUrl(), String.class);
});
assertEquals(401, exception.getRawStatusCode());
}
@Test
void test2_basicSuccess(){
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Basic "+ Base64.getEncoder().encodeToString(
"user:1111".getBytes()
));
HttpEntity entity = new HttpEntity(null, headers);
ResponseEntity<String> res = client.exchange(greetingUrl(), HttpMethod.GET, entity, String.class);
assertEquals("hello",res.getBody());
}
@Test
void test3_finalTest(){
ResponseEntity<List<User>> res = client1.exchange("http://localhost:" + port + "/rest/user/list",
HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {
});
assertEquals(3,res.getBody().size());
System.out.println(res.getBody());
}
}
'Spring > 1-5. Spring Security' 카테고리의 다른 글
OncePerRequestFilter란? (0) | 2023.11.24 |
---|---|
6) DaoAuthenticationManager와 UserDetailsService 사 (0) | 2023.06.11 |
4) Form Login과 Logout Filter (0) | 2023.06.04 |
3. Spring Security Authentication 구조와 매커니즘 (0) | 2023.06.04 |
2. Spring Security의 Filter (0) | 2023.06.04 |