layout : post
title : "Oauth2 (deprecated)"
category : Spring
최근 버전에서는 deprecated 되었지만
Authorization Server Config
Oauth2AuthorizationConfig 생성하고 인증 서버 활성화
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@Configuration
@EnableAuthorizationServer
public class Oauth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
public void configure(ClientDetailsServiceConfigurer clients) {
clients
.inMemory()
.withClient("user")
.secret("{bcrypt}$2y$12$g9xqwex/OWERjzqaXe9SQd5jvpwfsSX5wl8TAgehqADHUUctm") // password
.authorizedGrantTypes("client_credentials") // client_credentials 추가
.accessTokenValiditySeconds(60 * 60 * 24 * 7)
.scopes("read_profile");
}
}
- scopes : 인증후 얻은 accessToken으로 접근할 수 있는 리소스 범위
- accessTokenValiditySeconds : 발급된 accessToken 유효시간(초)
SpringSecurity Config 생성
import lombok.AllArgsConstructor;
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 java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated().and()
.formLogin().and()
.httpBasic();
makeAuthorizationRequestHeader(); //curl Authorization 에 사용
}
private static void makeAuthorizationRequestHeader() throws UnsupportedEncodingException {
String oauthClientId = "root";
String oauthClientSecret = "1234";
Base64.Encoder encoder = Base64.getEncoder();
String toEncodeString = String.format("%s:%s", oauthClientId, oauthClientSecret);
String authorizationRequestHeader = "Basic " + encoder.encodeToString(toEncodeString.getBytes(StandardCharsets.UTF_8));
}
}
ResourceServerConfig 생성
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and()
.requestMatchers().antMatchers("/api/**");
}
}
access token 발급
curl -X POST \
http://localhost:8080/oauth/token \
-H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&scope=read_profile'
다음과 같이 응답이 온다.
{
"access_token": "4f21958-4c90-4c1e-982e-626858eac8",
"token_type": "bearer",
"expires_in": 514,
"scope": "read_profile"
}
엑세스 토큰을 이용하여 접속할 수 있다.
curl -X GET \
http://localhost:8080/api/404 \
-H 'Authorization: Bearer 4f21958-4c90-4c1e-982e-626858eac8'
gradle 사용시
implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.7.RELEASE'
create table oauth_client_details (
client_id VARCHAR(256) PRIMARY KEY,
resource_ids VARCHAR(256),
client_secret VARCHAR(256),
scope VARCHAR(256),
authorized_grant_types VARCHAR(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(4096),
autoapprove VARCHAR(256)
);
insert into oauth_client_details (client_id, client_secret, resource_ids, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove)
values ('user', '1234', null, 'read,write', 'client_credentials', null, 'ROLE_MY_CLIENT', 60 * 60 * 24 * 7, 2592000, null, null);
'IT > Spring' 카테고리의 다른 글
2021-01-12-log4j2 (0) | 2023.02.28 |
---|---|
2021-01-06-Spring-Injection (0) | 2023.02.27 |
2021-01-06-JPA-모델마다-다른-스키마-사용 (0) | 2023.02.27 |
2021-01-06-bean-thread-safe (0) | 2023.02.27 |
SSH 연결하기 (0) | 2020.07.27 |
댓글