[SPRING] 동일한 REST API에 대한 기본 인증과 양식 로그인 결합
SPRING동일한 REST API에 대한 기본 인증과 양식 로그인 결합
동일한 REST 서비스에 대한 기본 인증 및 양식 로그인을 설정하는 방법이 있습니까? 나는 로그 인한 후 사용자가 웹 브라우저를 통해 로그인하고 curl을 실행하는 커맨드 라인에서이 서비스를 실행할 수있게하고 싶다 -u username : password hostname.com/api/process 이제이 글을 보았습니다 : 스프링 보안 Javaconfig를 이용한 기본 및 폼 기반 인증 하지만 내가하려는 일과는 조금 다릅니다. 이걸 봄에 만들 수있는 방법이 있을까요? 내가 지금 가지고있는 것은 이것이다.
package com.my.company.my.app.security;
import org.slf4j.LoggerFactory;
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;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/js/**", "/css/**")
.permitAll();
http
.authorizeRequests()
.antMatchers("/api/**")
.authenticated()
.and()
.httpBasic();
http
.authorizeRequests()
.antMatchers("/","/index")
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.defaultSuccessUrl("/monitor")
.failureUrl("/login?error")
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
.and()
.logout()
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.csrf()
.disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username=?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username=?");
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
유일한 문제는 hostname.com/index 또는 hostname.com/이 기본 인증 자격 증명을 묻는 창 팝업 대신 호출되면 내 로그인 페이지로 리디렉션되지 않는다는 것입니다.
해결법
-
==============================
1.아래와 같이 여러 HTTP 구성을 사용하면 쉽게이 작업을 수행 할 수 있습니다.이 코드는 여러 HTTP 구성만을 설명합니다. 나는 스프링 보안과 관련된 다른 필수 구성, 예를 들어 authenticationManger 등을 잘 알고 있다고 가정하고 있습니다.
아래와 같이 여러 HTTP 구성을 사용하면 쉽게이 작업을 수행 할 수 있습니다.이 코드는 여러 HTTP 구성만을 설명합니다. 나는 스프링 보안과 관련된 다른 필수 구성, 예를 들어 authenticationManger 등을 잘 알고 있다고 가정하고 있습니다.
@EnableWebSecurity public class MultiHttpSecurityCustomConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password") .roles("USER", "ADMIN"); } @Configuration @Order(1) public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/api/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic(); } } @Configuration public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and().formLogin(); } } }
스프링 보안 공식 링크를 참조하십시오 : Multiple HttpSecurity
또한 Spring Security로 Secure REST Services를 체크 아웃 할 것을 권장합니다.
문제가 발생하면 언제든지 말씀해주십시오!
from https://stackoverflow.com/questions/33739359/combining-basic-authentication-and-form-login-for-the-same-rest-api by cc-by-sa and MIT license
'SPRING' 카테고리의 다른 글
[SPRING] 바인딩 전 JSR-303 유형 검사 (0) | 2019.01.01 |
---|---|
[SPRING] "/"가 포함 된 @pathVariable을 갖는 Spring @RequestMapping을 일치시키는 방법은 무엇입니까? (0) | 2019.01.01 |
[SPRING] 스프링 부트 OAuth2 싱글 사인 오프 (로그 아웃) (0) | 2019.01.01 |
[SPRING] 스프링 부트 CORS 필터 - CORS 프리 플라이트 채널이 성공하지 못함 (0) | 2019.01.01 |
[SPRING] @Before 메서드 전에 @Sql을 실행하는 방법 (0) | 2019.01.01 |