>  기사  >  Java  >  Java API 개발에서 보안 인증을 위해 Spring Security OAuth 사용

Java API 개발에서 보안 인증을 위해 Spring Security OAuth 사용

WBOY
WBOY원래의
2023-06-18 08:01:271683검색

Java API 개발의 일반적인 요구 사항은 사용자 인증 및 권한 부여 기능을 구현하는 것입니다. 보다 안전하고 안정적인 API 서비스를 제공하기 위해서는 특히 인증 기능이 중요해졌습니다. Spring Security OAuth는 Java API에서 인증 기능을 구현하는 데 도움을 줄 수 있는 뛰어난 오픈 소스 프레임워크입니다. 이 기사에서는 보안 인증을 위해 Spring Security OAuth를 사용하는 방법을 소개합니다.

  1. Spring Security OAuth란 무엇인가요?

Spring Security OAuth는 Spring Security 프레임워크의 확장으로, OAuth 인증 및 권한 부여 기능을 구현하는 데 도움이 됩니다.

OAuth는 타사 애플리케이션에 리소스 액세스 권한을 부여하기 위한 개방형 표준입니다. 이는 비즈니스 로직 분리 및 보안 애플리케이션을 달성하는 데 도움이 될 수 있습니다. OAuth 인증 프로세스에는 일반적으로 다음 역할이 포함됩니다.

  • 사용자: 리소스 소유자
  • 클라이언트: 사용자 리소스에 액세스하는 데 적용되는 애플리케이션
  • 인증 서버: 사용자 인증을 처리하는 서버 : 사용자 리소스 서버 저장
  • Spring Security OAuth는 OAuth 인증 프로세스에서 4개의 엔드포인트를 구현합니다:
  1. /oauth/authorize: 인증 서버의 인증 엔드포인트
/oauth/token: 인증 서버의 토큰 끝점

/oauth/confirm_access: 클라이언트가 인증을 확인하는 끝점
  • /oauth/error: 인증 서버 오류 정보에 대한 끝점
  • Spring Security OAuth는 OAuth의 네 가지 인증 모드를 구현합니다. 2.0:
  • 인증 코드 모드: 사용 시나리오는 애플리케이션이 시작될 때 사용자 인증이 필요하다는 것입니다.
비밀번호 모드: 사용 시나리오는 클라이언트가 사용자 자격 증명을 독립적으로 관리한다는 것입니다.

단순 모드: 사용 시나리오는 다음과 같습니다. 클라이언트는 브라우저에서 실행되며 클라이언트 측 사용자 자격 증명 보호가 필요하지 않습니다.
  • 클라이언트 모드: 사용 시나리오는 클라이언트가 사용자 인증을 요구하지 않으며 요청된 액세스 토큰은 클라이언트 자체만 나타냅니다.
  • Spring Security OAuth 종속성 추가
  • Spring을 프로젝트 Security OAuth 종속성에 추가하세요. pom.xml에서 다음을 구성합니다.
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
  1. 인증 서버 구성

인증을 위한 인증 서버를 정의해야 합니다. Spring Security OAuth에서는 OAuth2 인증 서버를 활성화하고 AuthorizationServerConfigurer 인터페이스를 구현하여 인증 서버를 정의할 수 있습니다.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    TokenStore tokenStore;

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client")
            .secret("{noop}secret")
            .authorizedGrantTypes("client_credentials", "password")
            .scopes("read", "write")
            .accessTokenValiditySeconds(3600)
            .refreshTokenValiditySeconds(7200);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
            .authenticationManager(authenticationManager);
    }
}
    위 코드에서는 메모리 기반 클라이언트 세부 정보 서비스를 정의하고 인증 유형을 client_credentials 및 비밀번호로 구성합니다. 또한 액세스 토큰의 유효 기간과 새로 고침 토큰의 유효 기간도 지정합니다. 또한 엔드포인트와 필수 tokenStore 및 인증 관리자를 정의합니다.
리소스 서버 구성

Spring Security OAuth 보안 인증을 사용하려면 리소스 서버도 구성해야 합니다. Spring Security OAuth에서는 ResourceServerConfigurer 인터페이스를 구현하여 리소스 서버를 정의할 수 있습니다.

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .anyRequest().permitAll();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer config) throws Exception {
        config.resourceId("my_resource_id");
    }
}
    위 코드에서는 다른 요청이 익명 액세스를 허용하는 동안 인증을 제공하기 위해 /api/**를 정의했습니다. 또한 후속 인증 프로세스에 사용하기 위해 리소스 ID "my_resource_id"를 구성합니다.
웹 보안 구성

Spring Security OAuth 보안 인증을 사용하려면 웹 보안도 구성해야 합니다. Spring Security OAuth에서는 SecurityConfigurer 인터페이스를 구현하여 보안을 정의할 수 있습니다.

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("{noop}password")
            .roles("USER");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/oauth/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .permitAll();
    }
}
    위 코드에서는 메모리 기반 사용자 세부 정보 서비스를 정의하고 인증이 필요한 요청을 선언합니다(즉, /oauth/** 이후의 경로는 인증이 필요하고 다른 경로는 익명 액세스가 가능합니다). 또한 사용자가 애플리케이션에 로그인할 수 있는 간단한 양식 로그인을 구성했습니다.
UserDetailsService 구현

보안 인증에 사용하려면 UserDetailsService 인터페이스를 구현해야 합니다. 여기서는 사용자 계정과 비밀번호를 저장하기 위해 메모리를 직접 사용하며 데이터베이스 작업은 포함하지 않습니다.

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("user".equals(username)) {
            return new User("user", "{noop}password",
                    AuthorityUtils.createAuthorityList("ROLE_USER"));
        } else {
            throw new UsernameNotFoundException("username not found");
        }
    }
}
  1. API 구현

다음으로 간단한 API를 구현해야 합니다. 클라이언트에 인사말을 반환하기 위해 /api/** 경로 아래에 getGreeting() API를 추가했습니다.

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/greeting")
    public String getGreeting() {
        return "Hello, World!";
    }
}
  1. 승인 프로세스 테스트

마지막으로 승인 프로세스가 예상대로 작동하는지 테스트해야 합니다. 먼저 인증 코드 모드를 사용하여 인증 코드를 얻습니다.

http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8080&scope=read
    브라우저에서 위의 URL을 방문하면 인증을 위해 사용자 이름과 비밀번호를 입력하라는 메시지가 표시됩니다. 사용자 이름 user 및 비밀번호 비밀번호를 입력하고 승인을 클릭하면 http://localhost:8080/?code=xxx로 리디렉션됩니다. 여기서 xxx는 승인 코드입니다.
  1. 다음으로 비밀번호 패턴을 사용하여 액세스 토큰을 얻습니다.
curl -X POST 
  http://localhost:8080/oauth/token 
  -H 'content-type: application/x-www-form-urlencoded' 
  -d 'grant_type=password&username=user&password=password&client_id=client&client_secret=secret'

액세스 토큰과 새로 고침 토큰이 포함된 JSON 응답을 받게 됩니다.

{
    "access_token":"...",
    "token_type":"bearer",
    "refresh_token":"...",
    "expires_in":3600,
    "scope":"read"
}

이제 이 액세스 토큰을 사용하여 API 서비스에 액세스할 수 있습니다.

curl -X GET 
  http://localhost:8080/api/greeting 
  -H 'authorization: Bearer xxx'

여기서 xxx는 액세스 토큰입니다. "Hello, World!"라는 인사말이 포함된 JSON 응답을 받게 됩니다.

이 글에서는 보안 인증을 위해 Spring Security OAuth를 사용하는 방법을 소개합니다. Spring Security OAuth는 OAuth 인증 프로세스에서 모든 역할을 구현하는 데 도움이 되는 매우 강력한 프레임워크입니다. 실제 적용에서는 다양한 보안 요구 사항에 따라 다양한 인증 모드와 서비스 구성을 선택할 수 있습니다.

위 내용은 Java API 개발에서 보안 인증을 위해 Spring Security OAuth 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.