IT

spring security in action chap.13

프로개발러 2023. 9. 4. 15:14
반응형

 

권한부여서버 직접 구축하는 방법

 

자체적으로 권한부여서버를 구성하기 위해서는 아래 dependency를 추가

 

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

 

그리고 기존 configuration 위에

enableauthorizationserver를 어노테이션으로 지정

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

 

 

https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/config/annotation/web/configuration/EnableAuthorizationServer.html

 

EnableAuthorizationServer (OAuth for Spring Security 2.4.0.BUILD-SNAPSHOT API)

 

docs.spring.io

 

간단한 어노테이션만 선언하여 권한서버구성을 가능하도록 해줌.

Convenience annotation for enabling an Authorization Server

 

 

 

여기까지 했다면 다음은 아래 3가지를 구현해줘야 함.

 

사용자 관리 구현
하나 이상의 클라이언트 등록
어떤그랜트 유형 지원할지 결정

 

 

사용자 관리는 websecurityconfig에서 구현한다.

 

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService uds() {
        var uds = new InMemoryUserDetailsManager();

        var u = User.withUsername("john")
                .password("12345")
                .authorities("read")
                .build();

        uds.createUser(u);

        return uds;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();
    }
}

InMemoryUserDetailsManager를 통해서 클라이언트 등록이 가능하다.

 

사용자가 /login페이지에서 암호가 일치한다면(john/12345)

클라이언트를 통해서 권한서버에게 권한을 요청하는 것이다.

 

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig
        extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret("secret")
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("read");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }

}

 

그리고 이 부분을 통해서 

토큰을 발급해주는 권한서버를 구현해 줄 수 있다.

 

 

원래는 

C:\Users\user>curl -v -XPOST -u client:secret http://localhost:8080/oauth/token?grant_type=password&username=john&password=12345
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
* Server auth using Basic with user 'client'
> POST /oauth/token?grant_type=password HTTP/1.1
> Host: localhost:8080
> Authorization: Basic Y2xpZW50OnNlY3JldA==
> User-Agent: curl/8.0.1
> Accept: */*
>
< HTTP/1.1 400
< Cache-Control: no-store
< Pragma: no-cache
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: DENY
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Mon, 04 Sep 2023 07:00:28 GMT
< Connection: close
<
{"error":"invalid_grant","error_description":"자격 증명에 실패하였습니다."}* Closing connection 0
'username'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.
'password'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.

 

 

 

원래는 access_toke과 값이 나와야 하는데

뭔지 모르겠는데 오류발생...

 

2023-09-04 16:00:28.560  WARN 49804 --- [nio-8080-exec-8] o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error: InvalidGrantException, 자격 증명에 실패하였습니다.

 

 

콘솔에는 자격증명에 실패했다고 나옴.

 

참고로 어떤 그랜트 유형을 사용할 것인지는

아래에서 설정.

 

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("client")
            .secret("secret")
            .authorizedGrantTypes("password", "refresh_token")
            .scopes("read");
}

 

어떤 유형의 그랜트타입을 제공할 것인지는

xsd파일에 나와 있음.

<xs:attribute name="authorized-grant-types" type="xs:string">
   <xs:annotation>
      <xs:documentation>
         Grant types that are authorized for the
         client to use
         (comma-separated). Currently defined
         grant types
         include
         "authorization_code", "password", "assertion", and
         "refresh_token". Default value is
         "authorization_code,refresh_token".
      </xs:documentation>
   </xs:annotation>
</xs:attribute>

 

반응형