<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="https://publishpress.com/"
	>

<channel>
	<title>Authorization Archives - 아빠프로그래머의 좌충우돌 개발하기!</title>
	<atom:link href="https://www.daddyprogrammer.org/post/tag/authorization/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.daddyprogrammer.org/post/tag/authorization/</link>
	<description>기저귀 갈면서 코딩해야 프로다!</description>
	<lastBuildDate>Thu, 17 Feb 2022 09:54:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://www.daddyprogrammer.org/wp-content/uploads/2019/04/cropped-spring-bird-2295431_960_720-300x300.jpg</url>
	<title>Authorization Archives - 아빠프로그래머의 좌충우돌 개발하기!</title>
	<link>https://www.daddyprogrammer.org/post/tag/authorization/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Spring Boot Oauth2 – ResourceServer : 비대칭키를 이용한 서명(asymmetric keys to do the signing process)</title>
		<link>https://www.daddyprogrammer.org/post/1890/spring-boot-oauth2-resourceserver-asymmetric-keys-to-do-the-signing-process/</link>
					<comments>https://www.daddyprogrammer.org/post/1890/spring-boot-oauth2-resourceserver-asymmetric-keys-to-do-the-signing-process/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Fri, 26 Apr 2019 15:35:08 +0000</pubDate>
				<category><![CDATA[Oauth2]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Authorization]]></category>
		<category><![CDATA[비대칭키암호화]]></category>
		<category><![CDATA[ResourceServer]]></category>
		<category><![CDATA[Asymmetric keys]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=1890</guid>

					<description><![CDATA[<p>이번 시간에는 인증서버와 리소스 서버간에 토큰 인증시 서명 방식을 변경해 보겠습니다. 서명이란 서로간에 신뢰성있는 통신을 하기 위한 절차라고 생각하면 됩니다. 최신 소스는 아래 GitHub 주소를 참고해 주세요. https://github.com/codej99/SpringOauth2AuthorizationServer.githttps://github.com/codej99/SpringOauth2ResourceServer.git 대칭키 서명 A(리소스서버)가 B(인증서버)에게 데이터를 보낼때 B의 sign으로 암호화 해서 보내면 B는 자신의 sign으로 데이터를 복호화해서 볼 수 있습니다. B는 데이터를 전달받기 전에 A에게 자신의 sign정보(비밀키)를 공유해주기만 [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1890/spring-boot-oauth2-resourceserver-asymmetric-keys-to-do-the-signing-process/">Spring Boot Oauth2 – ResourceServer : 비대칭키를 이용한 서명(asymmetric keys to do the signing process)</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">이번 시간에는 인증서버와 리소스 서버간에 토큰 인증시 서명 방식을 변경해 보겠습니다. 서명이란 서로간에 신뢰성있는 통신을 하기 위한 절차라고 생각하면 됩니다. </p>



<p class="wp-block-paragraph"><span class="has-inline-color has-vivid-red-color"><strong> 최신 소스는 아래 GitHub 주소를 참고해 주세요.</strong></span></p>



<p class="wp-block-paragraph"><strong><a href="https://github.com/codej99/SpringOauth2AuthorizationServer.git">https://github.com/codej99/SpringOauth2AuthorizationServer.git</a><br><a href="https://github.com/codej99/SpringOauth2ResourceServer.git">https://github.com/codej99/SpringOauth2ResourceServer.git</a></strong></p>



<h3 class="wp-block-heading">대칭키 서명</h3>



<p class="wp-block-paragraph">A(리소스서버)가 B(인증서버)에게 데이터를 보낼때 B의 sign으로 암호화 해서 보내면 B는 자신의 sign으로 데이터를 복호화해서 볼 수 있습니다. B는 데이터를 전달받기 전에 A에게 자신의 sign정보(비밀키)를 공유해주기만 하면 됩니다. 그런데 이 방식은 B의 sign이 노출되면 다른 C가 B에게 보내진 데이터를 가로채서 볼 수 있는 단점이 있습니다. 위의 방식은 양쪽에 같은 sign키를 공유하기 때문에 문제가 됩니다. 이전 장에서 인증서버와 리소스서버의 application.yml 파일을 보면 아래와 같이 동일한 signKey를 공유하고 있음을 확인 할 수 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">security:
  oauth2:
    jwt:
      signkey: 123@#$</pre>



<h3 class="wp-block-heading">비대칭키를 이용한 서명(asymmetric keys to do the signing process)</h3>



<p class="wp-block-paragraph">비대칭키 방식은 B(인증서버)가 비밀키와 공개키 1쌍을 만듭니다. 데이터는 공개키로 암호화 되는데 복호화는 비밀키로만 가능합니다. B(인증서버)는 A(리소스서버)에게 공개키를 공유하고 해당 키로 암호화하여 데이터를 전달해 달라고 합니다. 이렇게 되면 공개키와 암호화된 데이터가 다른곳에 노출 되더라도, 다른 누군가가 데이터를 복호화해 볼 수 없기 때문에 결과적으로 높은 보안의 데이터 통신이 가능하게 됩니다.</p>



<h3 class="wp-block-heading">Java KeyStore (JKS) &#8211; 자바 키 저장소</h3>



<p class="wp-block-paragraph">java에서는 keytool을 제공하여 비대칭키를 생성할 수 있는 방법을 제공합니다. 보통 비대칭키 암호화는 RSA 알고리즘을 많이 사용하며 다음과 같이 생성할 수 있습니다.  <br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ keytool -genkeypair -alias Key의 별칭
                    -keyalg RSA 
                    -keypass Key 암호
                    -keystore 저장될 key의 파일명 
                    -storepass 저장될 파일의 암호</pre>



<p class="wp-block-paragraph">keytool 명령을 실행하면 실행한 디렉토리에 *.jks 파일이 생성됩니다. 해당 파일은 비밀키와 공개키 정보를 담고 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ keytool -genkeypair -alias oauth2jwt -keyalg RSA -keypass oauth2jwtpass -keystore oauth2jwt.jks -storepass oauth2jwtpass
이름과 성을 입력하십시오.
  [Unknown]:
조직 단위 이름을 입력하십시오.
  [Unknown]:
조직 이름을 입력하십시오.
  [Unknown]:
구/군/시 이름을 입력하십시오?
  [Unknown]:
시/도 이름을 입력하십시오.
  [Unknown]:
이 조직의 두 자리 국가 코드를 입력하십시오.
  [Unknown]:
CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown이(가) 맞습니까?
  [아니오]:  y</pre>



<h3 class="wp-block-heading">공개키 정보 확인</h3>



<p class="wp-block-paragraph">생성한 jks 파일에서 다음과 같이 공개키 정보를 확인 할 수 있습니다.<br>클라이언트에는 &#8212;&#8211;BEGIN PUBLIC KEY&#8212;&#8211; 공개키 &#8212;&#8211;END PUBLIC KEY&#8212;&#8211; 내용을 전달하면 됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ keytool -list -rfc --keystore oauth2jwt.jks | openssl x509 -inform pem -pubkey
키 저장소 비밀번호 입력:  oauth2jwtpass
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArJerQDKo7Vwl2an9UEZD
9npx8vXoB+setdeZn5OKEntdpdXMdc1KE07Q8aejXnEdzTHqeWxfdctyJ0FZzphX
PSfw8IzjjElmi4GoM5Aqh0ecPUjRrSHrE3EXwxagfoRy1igfD5ALCH7VIOvf3erU
QKhAY+ARdQzNn2+d1V9y6atnPPwbjflm2Ke+S9K+Q+dvIpIbotRG7rJqO9RSn89Q
E6CcNP0LhaL6FFt9mtCEtOAlZyJHLO/CJ51XQzfGP4cYXCUQT5TC0yRKmPlRuurE
gfgmiAYl6XD1o3iui3vEJzNLN9nrbte4rjc+Rqv3aE23hu3f8QImNzdSZo6HJhQC
NwIDAQAB
-----END PUBLIC KEY-----
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEJg3+SjANBgkqhkiG9w0BAQsFADBsMRAwDgYDVQQGEwdV
bmtub3duMRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYD
VQQKEwdVbmtub3duMRAwDgYDVQQLEwdVbmtub3duMRAwDgYDVQQDEwdVbmtub3du
MB4XDTE5MDQyNjE1MjAzMloXDTE5MDcyNTE1MjAzMlowbDEQMA4GA1UEBhMHVW5r
bm93bjEQMA4GA1UECBMHVW5rbm93bjEQMA4GA1UEBxMHVW5rbm93bjEQMA4GA1UE
ChMHVW5rbm93bjEQMA4GA1UECxMHVW5rbm93bjEQMA4GA1UEAxMHVW5rbm93bjCC
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKyXq0AyqO1cJdmp/VBGQ/Z6
cfL16AfrHrXXmZ+TihJ7XaXVzHXNShNO0PGno15xHc0x6nlsX3XLcidBWc6YVz0n
8PCM44xJZouBqDOQKodHnD1I0a0h6xNxF8MWoH6EctYoHw+QCwh+1SDr393q1ECo
QGPgEXUMzZ9vndVfcumrZzz8G435ZtinvkvSvkPnbyKSG6LURu6yajvUUp/PUBOg
nDT9C4Wi+hRbfZrQhLTgJWciRyzvwiedV0M3xj+HGFwlEE+UwtMkSpj5UbrqxIH4
JogGJelw9aN4rot7xCczSzfZ627XuK43Pkar92hNt4bt3/ECJjc3UmaOhyYUAjcC
AwEAAaMhMB8wHQYDVR0OBBYEFGwU4l85+ogUly2Gv+cuzzRUvOs1MA0GCSqGSIb3
DQEBCwUAA4IBAQBaL58pMhDpSebvZFQeQkyDfc95lo/9b/+e109ryORIoX3zzbNO
O1v8By2qhjj11QS3skTv2jNE4h1wDxlF+EK6uom3Vc+yHH85/cRP6Ec9bK3+Vab7
BxE/r713L3I7rGbM0DMnTeDEDaCytN6TmwxeqJiUMePfWdKAZUV/WZeKTZxePfUf
ZK9J+FFEaua3hay2iY7s+eGPZ93rcNfrudARARdn34/coWx4lD8kh6At/K1qJrM2
7/QGMJeFP2zwBhhEhAwAN2ogad7cXOoy6OwcM0sMuZ+y5Vt2WKFLbHtRPj1V5mhk
Nq/ACKliqWctpd8P5M/4Oat+zdyR3YjnU3+r
-----END CERTIFICATE-----</pre>



<h3 class="wp-block-heading">인증서버에 jks 설정 추가</h3>



<p class="wp-block-paragraph">keytool로 만든 jks 파일을 인증서버의 resources 아래에 복사합니다.</p>



<figure class="wp-block-image is-resized"><img decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_0.png" alt="" class="wp-image-1932" width="167" height="86" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_0.png 167w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_0-150x77.png 150w" sizes="(max-width: 167px) 100vw, 167px" /></figure>



<h3 class="wp-block-heading">Oauth2AuthorizationConfig의 TokenConverter 수정</h3>



<p class="wp-block-paragraph">sign키 공유방식은 주석처리하고 oauth2jwt.jks를 읽어 처리하는 방식을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
* jwt converter - signKey 공유 방식
*/
//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        converter.setSigningKey(signKey);
//        return converter;
//    }

/**
* jwt converter - 비대칭 키 sign
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new FileSystemResource("src/main/resources/oauth2jwt.jks"), "oauth2jwtpass".toCharArray());
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("oauth2jwt"));
    return converter;
}</pre>



<h3 class="wp-block-heading">리소스서버(api)에 공개키 등록</h3>



<p class="wp-block-paragraph">resources아래에 공키키 파일을 하나 만들어 공개키를 저장합니다.</p>



<figure class="wp-block-image is-resized"><img decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_public.png" alt="" class="wp-image-1954" width="153" height="69" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_public.png 153w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_public-150x68.png 150w" sizes="(max-width: 153px) 100vw, 153px" /></figure>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArJerQDKo7Vwl2an9UEZD
9npx8vXoB+setdeZn5OKEntdpdXMdc1KE07Q8aejXnEdzTHqeWxfdctyJ0FZzphX
PSfw8IzjjElmi4GoM5Aqh0ecPUjRrSHrE3EXwxagfoRy1igfD5ALCH7VIOvf3erU
QKhAY+ARdQzNn2+d1V9y6atnPPwbjflm2Ke+S9K+Q+dvIpIbotRG7rJqO9RSn89Q
E6CcNP0LhaL6FFt9mtCEtOAlZyJHLO/CJ51XQzfGP4cYXCUQT5TC0yRKmPlRuurE
gfgmiAYl6XD1o3iui3vEJzNLN9nrbte4rjc+Rqv3aE23hu3f8QImNzdSZo6HJhQC
NwIDAQAB
-----END PUBLIC KEY-----</pre>



<h3 class="wp-block-heading" id="mce_48">Oauth2ResourceServerConfig의 TokenConverter 수정</h3>



<p class="wp-block-paragraph">signKey공유방식은 주석처리하고 publicKey.txt를 읽어 처리하도록 Converer를 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">//    @Bean
//    public JwtAccessTokenConverter accessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        converter.setSigningKey(signKey);
//        return converter;
//    }

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("publicKey.txt");
    String publicKey = null;
    try {
        publicKey = IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}</pre>



<h3 class="wp-block-heading">테스트</h3>



<p class="wp-block-paragraph">인증서버(8081), 리소스서버(8080)을 스타트합니다. 인증서버에서 로그인하여 토큰을 생성합니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTYzMzQ0MDMsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjNjZGIwY2NhLWU2MzItNDhmMC1hNzJlLWJiYWYzZjhmNDI0ZiIsImNsaWVudF9pZCI6InRlc3RDbGllbnRJZCIsInNjb3BlIjpbInJlYWQiXX0.jZG2IOrKCyJkq8F-j_vr-0Kenurq8YgA9Z95Y4N_DMk3AvzxLMfq1GuyT2HmW6pCQTbQbFqFu1oG-QanihKLBCSD-u3BYvtbGheql-gFC0SjUwhk1JXYSpeOWIo-giS6wPaiB4ahkcLoAgVhg4tAw9nNiIySDBC8dwKnn8jIPxRPRNpp64C-cPncixeos5T3vX-AIZz48VTpotTR6zXqmM12D9nhVJw2UTaMrKK9uQ2z5WNuruiopSF-BCgWMlb1Iq6k9TnMXi0tG7dHyImw-CsMsWjLKBhciI8N2IH2MCyHufkxK8Vx-qg0yWT83VzWpktOl9P_sT2b9R-bNgPaRA",
"token_type": "bearer",
"refresh_token": null,
"expires_in": 35999,
"scope": "read"
}</pre>



<h3 class="wp-block-heading">리소스서버에서 JWT로 users api 호출</h3>



<p class="wp-block-paragraph">비대칭키 서명을 통해 정상적으로 JWT인증이 되는것을 확인합니다.</p>



<figure class="wp-block-image is-resized"><img fetchpriority="high" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3.png" alt="" class="wp-image-1962" width="766" height="548" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3.png 766w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3-150x107.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3-300x215.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3-696x498.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_3-587x420.png 587w" sizes="(max-width: 766px) 100vw, 766px" /></figure>



<h3 class="wp-block-heading">리소스 서버의 공개키를 다른 공개키로 변경할경우</h3>



<p class="wp-block-paragraph">이런 경우는 없겠지만 테스트 결과는 JWT를 복호화하지 못하여 invalid_token 오류가 발생하게 됩니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4.png" alt="" class="wp-image-1965" width="767" height="498" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4.png 767w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4-150x97.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4-300x195.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4-696x452.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jks_4-647x420.png 647w" sizes="auto, (max-width: 767px) 100vw, 767px" /></figure>



<p class="wp-block-paragraph">비대칭키 서명을 통하여 인증서버와 리소스서버간의 통신을 고도화해 보았습니다. HTTPS(SSL)도 기본적으로는 이러한 방식으로 데이터를 주고 받고 있습니다. 인터넷에서는 데이터 탈취가 가능한 요소가 많기 때문에 보호되어야 할 정보를 전달할때 서명은 신뢰있는 데이터 통신을 위해 매우 중요한 요소입니다.   </p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1890/spring-boot-oauth2-resourceserver-asymmetric-keys-to-do-the-signing-process/">Spring Boot Oauth2 – ResourceServer : 비대칭키를 이용한 서명(asymmetric keys to do the signing process)</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/1890/spring-boot-oauth2-resourceserver-asymmetric-keys-to-do-the-signing-process/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		
		<series:name><![CDATA[SpringBoot2로 Oauth2 서버 만들기]]></series:name>
	</item>
		<item>
		<title>Spring Boot Oauth2 &#8211; ResourceServer</title>
		<link>https://www.daddyprogrammer.org/post/1754/spring-boot-oauth2-resourceserver/</link>
					<comments>https://www.daddyprogrammer.org/post/1754/spring-boot-oauth2-resourceserver/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Thu, 25 Apr 2019 08:54:34 +0000</pubDate>
				<category><![CDATA[Oauth2]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[JWT]]></category>
		<category><![CDATA[ResourceServer]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Authorization]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=1754</guid>

					<description><![CDATA[<p>이번 장에서는 Spring Oauth2를 이용한 ResourceServer(api서버) 구축을 실습해보겠습니다. 이전 장에서 만든 AuthorizationServer와 연동하여 실습은 진행됩니다. 실습은 bearer 토큰 방식부터 진행합니다. 최신 소스는 아래 GitHub 주소를 참고해 주세요. https://github.com/codej99/SpringOauth2ResourceServer.git bearer token Flow 아래 내용 중 테두리를 친 부분이 리소스 서버에서 개발해야 할 사항입니다. Authorization Server 수정 이전 시간에 만들었던 AuthorizationSever 내용을 수정합니다. Oauth2AuthorizationConfig에서 bearer token방식으로 테스트 [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1754/spring-boot-oauth2-resourceserver/">Spring Boot Oauth2 &#8211; ResourceServer</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">이번 장에서는 Spring Oauth2를 이용한 ResourceServer(api서버) 구축을 실습해보겠습니다. 이전 장에서 만든 AuthorizationServer와 연동하여 실습은 진행됩니다. 실습은 bearer 토큰 방식부터 진행합니다. </p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-red-color">최신 소스는 아래 GitHub 주소를 참고해 주세요. </span><br><a href="https://github.com/codej99/SpringOauth2ResourceServer.git">https://github.com/codej99/SpringOauth2ResourceServer.git</a></strong></p>



<h2 class="wp-block-heading">bearer token Flow</h2>



<p class="wp-block-paragraph">아래 내용 중 테두리를 친 부분이 리소스 서버에서 개발해야 할 사항입니다. <br></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1.png" alt="" class="wp-image-1783" width="600" height="553" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1.png 1200w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-1024x944.png 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-768x708.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-150x138.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-300x277.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-696x641.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-1-456x420.png 456w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>



<h2 class="wp-block-heading">Authorization Server 수정</h2>



<p class="wp-block-paragraph">이전 시간에 만들었던 AuthorizationSever 내용을 수정합니다. Oauth2AuthorizationConfig에서 bearer token방식으로 테스트 하기 위해 다음과 같이 변경합니다. bearer토큰은 활성화 시키고 jwtToken 설정 부분은 주석 처리합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
* 토큰 정보를 DB를 통해 관리한다.
*
* @return
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints.tokenStore(new JdbcTokenStore(dataSource)).userDetailsService(userDetailService);
}

/**
* 토큰 발급 방식을 JWT 토큰 방식으로 변경한다. 이렇게 하면 토큰 저장하는 DB Table은 필요가 없다.
*
* @param endpoints
* @throws Exception
*/
//    @Override
//    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//        super.configure(endpoints);
//        endpoints.accessTokenConverter(jwtAccessTokenConverter()).userDetailsService(userDetailService);
//    }

/**
* jwt converter를 등록
*
* @return
*/
//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        converter.setSigningKey(signKey);
//        return converter;
//    }</pre>



<h3 class="wp-block-heading">/oauth/check_token 활성화</h3>



<p class="wp-block-paragraph">Resource서버에서 token 검증 요청을 Authorization서버로 보낼때 /oauth/check_token을 호출하는데, 해당 요청을 받기 위해 Oauth2AuthorizationConfig에 아래 설정을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()") //allow check token
            .allowFormAuthenticationForClients();
}</pre>



<h2 class="wp-block-heading">ResourceServer 구현</h2>



<p class="wp-block-paragraph">새로운 프로젝트를 하나 생성합니다.<br><strong>&gt;&gt; <a rel="noreferrer noopener" aria-label="Intellij Community 프로젝트생성 (새탭으로 열기)" href="http://www.daddyprogrammer.org/post/19/spring-boot2-start-intellij" target="_blank">Intellij Community 프로젝트생성</a></strong></p>



<p class="wp-block-paragraph">신규 프로젝트를 초기 구성하는데 어려움이 있다면 Spring initializr를 통해 간편하게 프로젝트를 생성할 수 있습니다. 다음 포스팅을 참고해 주세요.<br>&gt;&gt;&nbsp;<strong><a rel="noreferrer noopener" href="http://www.daddyprogrammer.org/post/1212/springboot2-create-by-spring-initializr/" target="_blank">Spring initializr로 Spring 프로젝트 생성하기</a></strong></p>



<h3 class="wp-block-heading">build.gradle 수정</h3>



<p class="wp-block-paragraph">AuthorizationServer와 내용은 동일합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plugins {
    id 'org.springframework.boot' version '2.1.4.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.rest'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-security:2.1.2.RELEASE'
    implementation 'org.springframework.cloud:spring-cloud-starter-oauth2:2.1.2.RELEASE'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}</pre>



<h3 class="wp-block-heading">application.yml 수정</h3>



<p class="wp-block-paragraph">테스트시 인증서버와 리소스 서버를 동시에 띄워야 하므로 port는 8080으로 합니다. 아래 내용에서 주목해서 볼 부분은 하단의 security관련 설정입니다.<br>리소스 서버는 인증서버에 토큰 체크를 요청해야 하므로 요청시 필요한 데이터인client-id, client-secret, 토큰 체크 uri을 설정해 놓습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">server:
  port: 8080

spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
  datasource:
    url: jdbc:h2:tcp://localhost/~/test
    driver-class-name: org.h2.Driver
    username: sa
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    properties.hibernate.hbm2ddl.auto: update
    showSql: true

security:
  oauth2:
    client:
      client-id: testClientId
      client-secret: testSecret
    resource:
      token-info-uri: http://localhost:8081/oauth/check_token</pre>



<h3 class="wp-block-heading">리소스 서버 Config 생성</h3>



<p class="wp-block-paragraph">@EnableResourceServer를 선언하여 리소스 서버임을 세팅합니다. Spring security 설정시 H2 console접근이 차단되므로 해당 내용을 disable하기 위해 아래 내용을 추가합니다. <br>http.headers().frameOptions().disable() <br>users api는 read scope로 접근할 수 있는 리소스로 설정합니다.<br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.config;

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 Oauth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/v1/users").access("#oauth2.hasScope('read')")
                .anyRequest().authenticated();
    }
}</pre>



<h3 class="wp-block-heading">리소스 요청을 처리하는 Controller 작성</h3>



<p class="wp-block-paragraph">회원 리스트를 결과로 주는 UserController를 하나 생성합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.controller;

import com.rest.oauth2.entity.User;
import com.rest.oauth2.repo.UserJpaRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class UserController {

    private final UserJpaRepo userJpaRepo;

    @GetMapping(value = "/users")
    public List&lt;User> findAllUser() {
        return userJpaRepo.findAll();
    }
}</pre>



<h3 class="wp-block-heading">UserJpaRepo 생성</h3>



<p class="wp-block-paragraph">회원 정보를 조회할 JPA Repository를 선언합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.repo;

import com.rest.oauth2.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserJpaRepo extends JpaRepository&lt;User, Long> {
}</pre>



<h3 class="wp-block-heading">User entity 생성</h3>



<p class="wp-block-paragraph">회원 정보를 관리할 entity를 생성합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.entity;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
    @Id // pk
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long msrl;
    @Column(nullable = false, unique = true, length = 50)
    private String uid;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(length = 100)
    private String password;
    @Column(nullable = false, length = 100)
    private String name;
    @Column(length = 100)
    private String provider;

    @ElementCollection(fetch = FetchType.EAGER)
    @Builder.Default
    private List&lt;String> roles = new ArrayList&lt;>();

    @Override
    public Collection&lt;? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public String getUsername() {
        return this.uid;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isEnabled() {
        return true;
    }
}</pre>



<h3 class="wp-block-heading">bearer Token 테스트</h3>



<p class="wp-block-paragraph">Authorization서버(8081)와 Resource서버(8080)를 시작 합니다. 인증서버가 구동 되면 아래 주소를 실행하여 로그인하고 토큰을 얻습니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "access_token": "a9237159-ecd1-4d51-9c7a-4ee080160519", 
    "token_type": "bearer",
    "refresh_token": null,
    "expires_in": 35999,
    "scope": "read"
}</pre>



<p class="wp-block-paragraph">access토큰으로 리소스서버에 리소스를 요청합니다. 테스트는 postman을 이용합니다. (<a href="https://www.getpostman.com/downloads/" target="_blank" rel="noreferrer noopener" aria-label=" (새탭으로 열기)">https://www.getpostman.com/downloads/)</a><br>올바른 토큰으로 리소스를 요청하였을경우 아래와 같이 유저 정보를 얻을수 있음을 확인할 수 있습니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_1.png" alt="" class="wp-image-1814" width="697" height="918" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_1.png 697w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_1-150x198.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_1-300x395.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_1-319x420.png 319w" sizes="auto, (max-width: 697px) 100vw, 697px" /></figure>



<p class="wp-block-paragraph">요번에는 토큰을 변형시켜서 테스트를 실패 해보겠습니다. 당연하지만 invalid token이 결과로 오면서 실패합니다. 인증(Authorization)서버의 로그를 살펴보면 예외가 발생했음을 확인할 수 있습니다. 여기서 알 수 있는점은 bearer토큰으로 리소스를 요청할때는 token검증을 위해 인증서버의 확인이 필요하다는 점입니다. Flow의 내용이 검증 되었습니다. </p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2.png" alt="" class="wp-image-1815" width="812" height="547" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2.png 812w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2-768x517.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2-150x101.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2-300x202.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2-696x469.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_2-623x420.png 623w" sizes="auto, (max-width: 812px) 100vw, 812px" /></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_3.png" alt="" class="wp-image-1816" width="661" height="84" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_3.png 661w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_3-150x19.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_3-300x38.png 300w" sizes="auto, (max-width: 661px) 100vw, 661px" /></figure>



<h2 class="wp-block-heading">JWT Token을 통한 리소스 요청</h2>



<p class="wp-block-paragraph">이번에는 JWT방식으로 토큰을 변경하고 테스트 해보겠습니다. 인증서버의 세팅에서 아래와 같이 수정하여 JWT를 활성화시키고 서버를 리스타트 합니다. 인증 서버의 Oauth2AuthorizationConfig를 다음과 같이 수정합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
* 토큰 정보를 DB를 통해 관리한다.
*
* @return
*/
//    @Override
//    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//        endpoints.tokenStore(new JdbcTokenStore(dataSource)).userDetailsService(userDetailService);
//    }

/**
* 토큰 발급 방식을 JWT 토큰 방식으로 변경한다. 이렇게 하면 토큰 저장하는 DB Table은 필요가 없다.
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    super.configure(endpoints);
    endpoints.accessTokenConverter(jwtAccessTokenConverter()).userDetailsService(userDetailService);
}

/**
* jwt converter를 등록
*
* @return
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey(signKey);
    return converter;
}</pre>



<h3 class="wp-block-heading">리소스 서버의 설정 변경</h3>



<p class="wp-block-paragraph">application.yml 내용을 아래와 같이 변경합니다. bearer token 설정 부분은 주석처리하고 jwt 설정 내용을 추가합니다. signkey는 인증서버 세팅과 동일하게 세팅합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">security:
  oauth2:
#    client:
#      client-id: testClientId
#      client-secret: testSecret
#    resource:
#      token-info-uri: http://localhost:8081/oauth/check_token
    jwt:
      signkey: 123@#$</pre>



<h3 class="wp-block-heading">리소스 서버 Config 수정</h3>



<p class="wp-block-paragraph">Oauth2ResourceServerConfig 에 jwt 설정 내용을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Value("${security.oauth2.jwt.signkey}")
private String signKey;

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey(signKey);
    return converter;
}</pre>



<p class="wp-block-paragraph">인증서버에서 로그인 후 JWT토큰을 얻습니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTYyNDAzMDYsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjBlZjUxNzIxLTdkMTMtNDVmNi1hYzVkLTc1NjEwZDVlOWViMSIsImNsaWVudF9pZCI6InRlc3RDbGllbnRJZCIsInNjb3BlIjpbInJlYWQiXX0.QqDJTGSEhCJwUGD12uRIVOLuE-nuNkJmaxjZkXucHak",
"token_type": "bearer",
"refresh_token": null,
"expires_in": 35999,
"scope": "read"
﻿}</pre>



<p class="wp-block-paragraph">JWT 토큰으로 리소스를 요청합니다. JWT 토큰으로도 정상적인 결과를 얻을 수 있음을 확인하였습니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4.png" alt="" class="wp-image-1823" width="825" height="897" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4.png 825w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4-768x835.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4-150x163.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4-300x326.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4-696x757.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_4-386x420.png 386w" sizes="auto, (max-width: 825px) 100vw, 825px" /></figure>



<p class="wp-block-paragraph">이번엔 JWT토큰을 변조하여 예외 테스트를 합니다. invalid_token 예외가 발생합니다. 이때 확인해야 할 점은 인증서버의 로그입니다. 인증서버의 로그에는 bearer토큰 인증 실패 때와는 달리 예외 로그가 남아있지 않습니다. 이로써 알수 있는 점은 JWT의 경우 자체 토큰만으로도 검증이 가능하므로 인증서버를 통해 검증을 하지 않는다는 것입니다.  </p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5.png" alt="" class="wp-image-1826" width="746" height="560" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5.png 746w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-150x113.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-300x225.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-696x522.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-560x420.png 560w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-80x60.png 80w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/resource_5-265x198.png 265w" sizes="auto, (max-width: 746px) 100vw, 746px" /></figure>



<p class="wp-block-paragraph">간단한 리소스 서버를 완성하고 bearer토큰과 jwt토큰의 테스트까지 완료하였습니다. 더불어 테스트를 통해 bearer토큰과 jwt토큰의 차이점까지 정확히 알게 되었습니다. </p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1754/spring-boot-oauth2-resourceserver/">Spring Boot Oauth2 &#8211; ResourceServer</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/1754/spring-boot-oauth2-resourceserver/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
		
		<series:name><![CDATA[SpringBoot2로 Oauth2 서버 만들기]]></series:name>
	</item>
		<item>
		<title>Spring Boot Oauth2 &#8211; AuthorizationServer : DB처리, JWT 토큰 방식 적용</title>
		<link>https://www.daddyprogrammer.org/post/1287/spring-oauth2-authorizationserver-database/</link>
					<comments>https://www.daddyprogrammer.org/post/1287/spring-oauth2-authorizationserver-database/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Tue, 23 Apr 2019 02:38:17 +0000</pubDate>
				<category><![CDATA[Oauth2]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Authorization]]></category>
		<category><![CDATA[JWT]]></category>
		<category><![CDATA[AuthorizationServer]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=1287</guid>

					<description><![CDATA[<p>앞 장에서는 테스트를 위해 메모리에 정보를 올려놓고 테스트하였으나, 이번에는 DB를 사용해 처리할 수 있도록 개선해 보겠습니다. 최신 소스는 아래 GitHub 주소를 참고해 주세요. https://github.com/codej99/SpringOauth2AuthorizationServer.git 클라이언트 정보를 DB 사용하는 방식으로 수정. 로그인 시 회원 정보를 DB 사용하는 방식으로 수정. 인증 및 토큰 정보를 DB 사용하는 방식으로 수정. 클라이언트 정보를 DB 사용하는 방식으로 수정. resources 아래에 schema.sql [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1287/spring-oauth2-authorizationserver-database/">Spring Boot Oauth2 &#8211; AuthorizationServer : DB처리, JWT 토큰 방식 적용</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">앞 장에서는 테스트를 위해 메모리에 정보를 올려놓고 테스트하였으나, 이번에는 DB를 사용해 처리할 수 있도록 개선해 보겠습니다.</p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">최신 소스는 아래 GitHub 주소를 참고해 주세요.  </span><br><a rel="noreferrer noopener" aria-label=" (새탭으로 열기)" href="https://github.com/codej99/SpringOauth2AuthorizationServer.git" target="_blank">https://github.com/codej99/SpringOauth2AuthorizationServer.git</a></strong></p>



<ul class="wp-block-list"><li>클라이언트 정보를 DB 사용하는 방식으로 수정.</li><li>로그인 시 회원 정보를 DB 사용하는 방식으로 수정.</li><li>인증 및 토큰 정보를 DB 사용하는 방식으로 수정.</li></ul>



<h2 class="wp-block-heading">클라이언트 정보를 DB 사용하는 방식으로 수정.</h2>



<p class="wp-block-paragraph">resources 아래에 schema.sql 파일을 생성 후 다음 쿼리를 넣습니다. 해당 테이블은 클라이언트 정보를 넣는 테이블입니다. 서버가 start 될 때 해당 schema.sql에 내용이 있으면 실행됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">create table IF NOT EXISTS 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),
  web_server_redirect_uri VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additional_information VARCHAR(4096),
  autoapprove VARCHAR(256)
);</pre>



<h3 class="wp-block-heading">Oauth2AuthorizationConfig 수정</h3>



<p class="wp-block-paragraph">inMemory로 설정된 부분을 삭제하고 다음과 같이 설정을 수정합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Autowired
private DataSource dataSource;

/**
 * 클라이언트 정보 주입 방식을 jdbcdetail로 변경
 *
 * @param clients
 * @throws Exception
 */
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource).passwordEncoder(passwordEncoder);
}</pre>



<h3 class="wp-block-heading">Client 정보 insert</h3>



<p class="wp-block-paragraph">어드민&nbsp;화면이&nbsp;없으므로&nbsp;수동으로&nbsp;Client정보를&nbsp;1건&nbsp;입력합니다.&nbsp;Client정보를&nbsp;넣을 때&nbsp;secret정보는&nbsp;암호화하여&nbsp;넣어야&nbsp;합니다.&nbsp;암호화해서&nbsp;넣지&nbsp;않으면&nbsp;인증&nbsp;후에&nbsp;다음과&nbsp;같은&nbsp;오류가&nbsp;발생할&nbsp;수&nbsp;있습니다.<br><strong>There&nbsp;is&nbsp;no&nbsp;PasswordEncoder&nbsp;mapped&nbsp;for&nbsp;the&nbsp;id&nbsp;&#8220;null&#8221;</strong><br>그러므로&nbsp;아래와&nbsp;같이&nbsp;간단히 프로그램을 만들어&nbsp;암호화&nbsp;정보를&nbsp;얻습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api;

import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

public class EncodingTest {
    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        System.out.printf("testSecret : %s\n", passwordEncoder.encode("testSecret"));
    }
}</pre>



<p class="wp-block-paragraph">서버를 실행하고 h2 console에서 다음 쿼리를 실행합니다. secret 필드엔 위에서 얻은 암호화된 데이터를 넣습니다. 아래의 쿼리는 테스트 클라이언트를 하나 생성합니다. 서비스에서는 해당 테이블에 데이터를 넣을 수 있도록 운영 툴을 만들어 클라이언트를 관리할 수 있도록 합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">insert into oauth_client_details(client_id, resource_ids,client_secret,scope,authorized_grant_types,web_server_redirect_uri,authorities,access_token_validity,refresh_token_validity,additional_information,autoapprove)
values('testClientId',null,'{bcrypt}$2a$10$H2oQgFY7qCRHWqkvAV4P6ONy2v74wfr3fQv.xERw3BJYSqh/Gcgrq','read,write','authorization_code,refresh_token','http://localhost:8081/oauth2/callback','ROLE_USER',36000,50000,null,null);</pre>



<p class="wp-block-paragraph">DB의 클라이언트 정보로 인증이 되는지 테스트합니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<p class="wp-block-paragraph">로그인 후 아래처럼 토큰 정보가 출력되면 테스트가 성공한 것입니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "access_token":"5bf1b64e-d0fa-4f47-b747-aee27cf1dc0a",
    "token_type":"bearer",
    "refresh_token":"52ad7031-e8e8-45a3-87cb-72d5417078dd",
    "expires_in":29974,
    "scope":"read"
}</pre>



<p class="wp-block-paragraph">좀 더 확실한 테스트를 위해 h2 console에서 oauth_client_details의 데이터를 삭제하고 다시 인증을 시도해 봅니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">delete from oauth_client_details;</pre>



<p class="wp-block-paragraph">다시 인증을 시도하면 승인받을 클라이언트가 없으므로 아래와 같이 나오면서 실패하게 됩니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/invalid_client.png" alt="" class="wp-image-1336" width="329" height="96" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/invalid_client.png 438w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/invalid_client-150x44.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/invalid_client-300x88.png 300w" sizes="auto, (max-width: 329px) 100vw, 329px" /></figure>



<h2 class="wp-block-heading">로그인 시 사용하는 회원 정보를 DB에서 조회하도록  수정.</h2>



<h3 class="wp-block-heading">User entity 생성</h3>



<p class="wp-block-paragraph">회원 정보를 담을 User entity를 생성합니다. Security에 필요한 정보를 담기 위해 UserDetails를 상속받아 관련 필드를 Overriding 합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
    @Id // pk
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long msrl;
    @Column(nullable = false, unique = true, length = 50)
    private String uid;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(length = 100)
    private String password;
    @Column(nullable = false, length = 100)
    private String name;
    @Column(length = 100)
    private String provider;

    @ElementCollection(fetch = FetchType.EAGER)
    @Builder.Default
    private List&lt;String> roles = new ArrayList&lt;>();

    @Override
    public Collection&lt;? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public String getUsername() {
        return this.uid;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isEnabled() {
        return true;
    }
}</pre>



<h3 class="wp-block-heading">User Repo 생성</h3>



<p class="wp-block-paragraph">User 테이블에 질의 요청을 하기 위해 JpaRepository를 상속받아 UserJpaRepo를 생성합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.repo;

import com.rest.oauth2.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserJpaRepo extends JpaRepository&lt;User, Long> {
    Optional&lt;User> findByUid(String email);
}</pre>



<h3 class="wp-block-heading">로그인 정보의 유효성을 검증하기 위한 AuthenticationProvider 작성</h3>



<p class="wp-block-paragraph">회원 이름으로 DB를 조회하여 회원정보의 비밀번호와 입력된 비밀번호의 매칭 여부를 확인합니다. 회원이 없거나 비밀번호가 틀린 경우엔 Exception을 발생시키고, 로그인 정보가 유효한 경우 회원 정보와 권한 정보로 인증 정보를 생성하여 리턴합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Slf4j
@RequiredArgsConstructor
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private final PasswordEncoder passwordEncoder;

    private final UserJpaRepo userJpaRepo;

    @Override
    public Authentication authenticate(Authentication authentication) {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userJpaRepo.findByUid(name).orElseThrow(() -> new UsernameNotFoundException("user is not exists"));

        if (!passwordEncoder.matches(password, user.getPassword()))
            throw new BadCredentialsException("password is not valid");

        return new UsernamePasswordAuthenticationToken(name, password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class&lt;?> authentication) {
        return authentication.equals(
                UsernamePasswordAuthenticationToken.class);
    }
}</pre>



<h3 class="wp-block-heading">SpringSecurityConfig 수정</h3>



<p class="wp-block-paragraph">noOpPasswordEncoder 선언은 삭제합니다.<br>configure(AuthenticationManagerBuilder auth) 메서드는 위에서 생성한 CustomAuthenticationProvider를 사용하도록 설정합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .csrf().disable()
                .headers().frameOptions().disable()
                .and()
                .authorizeRequests().antMatchers("/oauth/**", "/oauth/token", "/oauth2/callback", "/h2-console/*").permitAll()
                .and()
                .formLogin().and()
                .httpBasic();
    }
}</pre>



<h3 class="wp-block-heading">PasswordEncoder 등록</h3>



<p class="wp-block-paragraph">WebMvcConfig에 다음 내용을 추가합니다. 기본 설정의 Encoder는 bcrypt암호화를 사용하게 됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}</pre>



<h3 class="wp-block-heading">테스트  User 등록</h3>



<p class="wp-block-paragraph">테스트 User를 생성하기 위해 UserJpaRepoTest를 하나 생성하고 실행합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/userjparepo.png" alt="" class="wp-image-1314" width="220" height="99" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userjparepo.png 440w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userjparepo-150x68.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userjparepo-300x135.png 300w" sizes="auto, (max-width: 220px) 100vw, 220px" /></figure>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@RunWith(SpringRunner.class)
@SpringBootTest
public class UserJpaRepoTest {
    @Autowired
    private UserJpaRepo userJpaRepo;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Test
    public void insertNewUser() {
        userJpaRepo.save(User.builder()
                .uid("happydaddy@gmail.com")
                .password(passwordEncoder.encode("1234"))
                .name("happydaddy")
                .roles(Collections.singletonList("ROLE_USER"))
                .build());
    }
}</pre>



<p class="wp-block-paragraph">위에서 입력한 회원 데이터로 로그인하여 Token을 얻을 수 있는지 테스트합니다. 이전에 client정보를 db에서 삭제했다면 다음과 같이 다시 넣고 테스트해야 합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">insert into oauth_client_details(client_id, resource_ids,client_secret,scope,authorized_grant_types,web_server_redirect_uri,authorities,access_token_validity,refresh_token_validity,additional_information,autoapprove)
values('testClientId',null,'{bcrypt}$2a$10$H2oQgFY7qCRHWqkvAV4P6ONy2v74wfr3fQv.xERw3BJYSqh/Gcgrq','read,write','authorization_code','http://localhost:8081/oauth2/callback','ROLE_USER',36000,50000,null,null);</pre>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/userid_db_info.png" alt="" class="wp-image-1342" width="262" height="189" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userid_db_info.png 349w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userid_db_info-150x108.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userid_db_info-300x217.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/userid_db_info-324x235.png 324w" sizes="auto, (max-width: 262px) 100vw, 262px" /></figure>



<p class="wp-block-paragraph">인증 이후에 아래와 같이 token을 얻을 수 있으면 성공입니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "access_token":"6fc01380-acd5-41a8-b9db-2bb540736247",
    "token_type":"bearer",
    "refresh_token":"52ad7031-e8e8-45a3-87cb-72d5417078dd",
    "expires_in":35999,
    "scope":"read"
}</pre>



<h2 class="wp-block-heading">인증 및 토큰 정보를 DB 사용하는 방식으로 수정</h2>



<p class="wp-block-paragraph">사실 위에서 회원이 승인한 정보나 토큰 정보 등은 DB에 저장되어 다음에 다시 참고되어야 합니다. 몇 번의 테스트를 거치며 눈치 채신 분도 있겠지만 테스트할 때마다 다시 앱 승인을 받아야 합니다. 이것은 서버를 리스타트 할 때마다 해당 정보가 초기화되기 때문입니다.  </p>



<p class="wp-block-paragraph">관련 정보를 저장하기 위한 테이블 생성을 위해  아래 DDL을 scheme.sql에 넣습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">create table IF NOT EXISTS oauth_client_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256)
);

create table IF NOT EXISTS oauth_access_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256),
  authentication LONGVARBINARY,
  refresh_token VARCHAR(256)
);

create table IF NOT EXISTS oauth_refresh_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication LONGVARBINARY
);

create table IF NOT EXISTS oauth_code (
  code VARCHAR(256), authentication LONGVARBINARY
);

create table IF NOT EXISTS oauth_approvals (
	userId VARCHAR(256),
	clientId VARCHAR(256),
	scope VARCHAR(256),
	status VARCHAR(10),
	expiresAt TIMESTAMP,
	lastModifiedAt TIMESTAMP
);</pre>



<p class="wp-block-paragraph">토큰 처리 시 DB를 사용하도록 Oauth2AuthorizationConfig에 다음 내용을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * 토큰 정보를 DB를 통해 관리한다.
 * @return
 */
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new JdbcTokenStore(dataSource));
}</pre>



<p class="wp-block-paragraph">다시 테스트를 합니다. 인증이 성공하면 token 정보를 h2 console에서 조회해 봅니다. 다음과 같이 조회가 되면 성공입니다. token 정보가 브라우저 화면에 출력된 것과 다른 이유는 token정보도 암호화되어 들어가기 때문입니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/db_token_info.png" alt="" class="wp-image-1351" width="482" height="68" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/db_token_info.png 643w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/db_token_info-150x21.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/db_token_info-300x42.png 300w" sizes="auto, (max-width: 482px) 100vw, 482px" /></figure>



<p class="wp-block-paragraph">이제 서버를 리스타트하고 인증을 재시도해봅니다.</p>



<p class="wp-block-paragraph">로그인 이후에 바로 토큰 정보를 얻을 수 있게 됩니다. 앱에 대한 승인은 최초에 1번만 수행되고 그 이후엔 물어보지 않게 되는 것입니다. OAUTH_ACCESS_TOKEN 테이블에는 로그인 후 인증한 정보가 회원의 id와 매핑되어 저장되어 있음을 확인할 수 있습니다. OAUTH_ACCESS_TOKEN 테이블에서 데이터를 지운 후 다시 인증을 하면 승인 요청이 뜨는 것을 확인할 수 있습니다.</p>



<h3 class="wp-block-heading">토큰 타입을 JWT로 변경</h3>



<p class="wp-block-paragraph">access_token은 bearer토큰 형식입니다. 단순히 암호화된 문자열이라고 보면 됩니다. bearer토큰으로 리소스 서버에 리소스를 요청하면 해당 토큰이 유효한지 그리고 토큰 인증한 회원이 누구인지 인증서버에 확인을 추가로 해야 합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5.jpeg" alt="" class="wp-image-1499" width="750" height="689" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5.jpeg 1500w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-1024x940.jpeg 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-768x705.jpeg 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-150x138.jpeg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-300x275.jpeg 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-696x639.jpeg 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-5-458x420.jpeg 458w" sizes="auto, (max-width: 750px) 100vw, 750px" /></figure>



<p class="wp-block-paragraph">JWT는 이러한 단점을 보완하기 위해 만들어진 토큰입니다. JWT 토큰은 Json String이 암호화된 문자열입니다. 그런데 bearer토큰과 다르게 token자체에 특정한 정보를 세팅할 수 있습니다. 따라서 JWT 토큰을 생성할 때 회원의 id, 권한 같은 인증에 필요한 정보를 세팅해두면 bearer토큰처럼 회원을 확인하기 위해 인증서버를 한번 더 거칠 필요가 없게 됩니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6.jpeg" alt="" class="wp-image-1500" width="750" height="635" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6.jpeg 1500w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-1024x867.jpeg 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-768x650.jpeg 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-150x127.jpeg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-300x254.jpeg 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-696x589.jpeg 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-6-496x420.jpeg 496w" sizes="auto, (max-width: 750px) 100vw, 750px" /></figure>



<h3 class="wp-block-heading">Oauth2AuthorizationConfig 수정</h3>



<p class="wp-block-paragraph">JdbcTokenStore는 주석 처리하고 jwtAccessTokenConverter를 사용하도록 설정합니다. JWT를 사용할 경우 토큰 자체로 인증정보가 관리되므로 token정보를 관리하는 Table은 사용하지 않게 됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * 토큰 정보를 DB를 통해 관리한다.
 *
 * @return
 */
//    @Override
//    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//        endpoints.tokenStore(new JdbcTokenStore(dataSource));
//    }

/**
 * 토큰 발급 방식을 JWT 토큰 방식으로 변경한다. 이렇게 하면 토큰 저장하는 DB Table은 필요가 없다.
 *
 * @param endpoints
 * @throws Exception
 */
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        endpoints.accessTokenConverter(jwtAccessTokenConverter());
}

/**
 * jwt converter를 등록
 *
 * @return
 */
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
        return new JwtAccessTokenConverter();
}</pre>



<h3 class="wp-block-heading">JWT 토큰 발급 테스트</h3>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<p class="wp-block-paragraph">인증 화면에서 로그인을 하면 다음과 같은 화면이 나옵니다. bearer 토큰일 때와 화면이 다른 것을 알 수 있습니다. JWT의 경우 토큰 자체 정보만을 이용하기 때문에 유저가 이전에 해당 클라이언트에 리소스를 허용했는지 여부를 알 수가 없습니다. 따라서 JWT토큰의 경우 리소스 요청은 간단해지지만 새로 인증할 때마다 아래처럼 리소스 접근 요청 화면이 뜨게 되는 단점이 생기게 됩니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/jwt-approval.jpg" alt="" class="wp-image-1462" width="347" height="113" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jwt-approval.jpg 463w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jwt-approval-150x49.jpg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/jwt-approval-300x98.jpg 300w" sizes="auto, (max-width: 347px) 100vw, 347px" /><figcaption>JWT로 토큰 타입을 세팅하고 인증시 화면</figcaption></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2.png" alt="" class="wp-image-1258" width="501" height="186" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2.png 1002w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-768x285.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-150x56.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-300x111.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-696x258.png 696w" sizes="auto, (max-width: 501px) 100vw, 501px" /><figcaption> bearer로 토큰 타입을 세팅하고 인증시 화면</figcaption></figure>



<p class="wp-block-paragraph">Authorize를 클릭하면 토큰을 얻을 수 있습니다. bearer토큰에 비해 사이즈가 커진 것을 확인할 수 있습니다. 부가적인 정보를 담아서 암호화한 토큰이라 그렇습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTYxMjg2MzYsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjE3YWJlYWQ5LWZhYjYtNGM0Yy05ZTk5LTU5NzQ4ZWExN2U5OSIsImNsaWVudF9pZCI6InRlc3RDbGllbnRJZCIsInNjb3BlIjpbInJlYWQiXX0.hZHHI6Egio8nThCNvPd1YRGcdrbq6bp5nN7zZOtbdus",
"token_type":"bearer",
"refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiMTdhYmVhZDktZmFiNi00YzRjLTllOTktNTk3NDhlYTE3ZTk5IiwiZXhwIjoxNTU2MTQyNjM2LCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiZWU4YjU5MjYtYTZlZi00N2I2LWJmOWUtNzkwMTczY2U4ZWYyIiwiY2xpZW50X2lkIjoidGVzdENsaWVudElkIn0.rCswE10Qbn2XLRwkvOX5dgXo_ByzV8ROiAsxHur7_e8",
"expires_in":35999,
"scope":"read"
}</pre>



<h2 class="wp-block-heading">refresh_token을 이용한 access_token 재발급 테스트</h2>



<p class="wp-block-paragraph">access_token은 refresh_token으로 갱신하여 재발급 받을 수 있습니다. JWT Token을 갱신하기 위해서는 아래와 같은 작업이 필요합니다.</p>



<h3 class="wp-block-heading">AuthorizationServerEndpoint에 userDetailService 세팅</h3>



<p class="wp-block-paragraph">refresh 토큰이 정상인지 확인하려면 회원 정보를 조회해봐야 하므로 다음과 같이 Oauth2AuthorizationConfig에 userDetailsService를 세팅해 줍니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">private final CustomUserDetailService userDetailService;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
 endpoints.accessTokenConverter(jwtAccessTokenConverter()).userDetailsService(userDetailService);
}</pre>



<h3 class="wp-block-heading">jwt signkey 세팅</h3>



<p class="wp-block-paragraph">이전 테스트까지는 signkey를 명시적으로 세팅하지 않아 시스템에서 자동으로 세팅되었습니다. 그렇게 되면 refresh토큰을 복호화할 때 signKey가 달라서 오류가 발생합니다. 그러므로 명시적인 signkey세팅이 필요합니다. </p>



<p class="wp-block-paragraph">application.yml에 다음 내용을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">security:
  oauth2:
    jwt:
      signkey: 123@#$</pre>



<p class="wp-block-paragraph">Oauth2AuthorizationConfig의 JwtAccessTokenConverter에 signkey를 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Value("${security.oauth2.jwt.signkey}")
private String signKey;

@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(signKey);
        return converter;
}</pre>



<p class="wp-block-paragraph">토큰 갱신 여부를 확인할 테스트 코드를 Oauth2Controller에 추가로 작성합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@GetMapping(value = "/token/refresh")
public OAuthToken refreshToken(@RequestParam String refreshToken) {

        String credentials = "testClientId:testSecret";
        String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Authorization", "Basic " + encodedCredentials);

        MultiValueMap&lt;String, String> params = new LinkedMultiValueMap&lt;>();
        params.add("refresh_token", refreshToken);
        params.add("grant_type", "refresh_token");
        HttpEntity&lt;MultiValueMap&lt;String, String>> request = new HttpEntity&lt;>(params, headers);
        ResponseEntity&lt;String> response = restTemplate.postForEntity("http://localhost:8081/oauth/token", request, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return gson.fromJson(response.getBody(), OAuthToken.class);
        }
        return null;
}</pre>



<h3 class="wp-block-heading">토큰 refresh 테스트</h3>



<p class="wp-block-paragraph">인증을 통해 아래와 같은 토큰 정보를 얻습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTYxMzE3MTEsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6Ijk5MTAxMTY5LWZlY2EtNDVlMS05YmU4LWJmY2M2YmIzNGI4OCIsImNsaWVudF9pZCI6InRlc3RDbGllbnRJZCIsInNjb3BlIjpbInJlYWQiXX0.INqTsuYEJ9BCXqf9Q0rZRKGj0euHbx-DJ6mi2N4rOB8",
"token_type":"bearer",
"refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiOTkxMDExNjktZmVjYS00NWUxLTliZTgtYmZjYzZiYjM0Yjg4IiwiZXhwIjoxNTU2MTQ1NDUyLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiODZhMDliYjctMzA2NS00NGQ5LWIxYjEtNWJlOGFlMjdlOWZkIiwiY2xpZW50X2lkIjoidGVzdENsaWVudElkIn0.fL51VTaLMHEf89Ao41nUrW-MzaNGBupg_4Us5nEtL_4",
"expires_in":35999,
"scope":"read"
}</pre>



<p class="wp-block-paragraph">위 결과의 refresh_token 값으로 아래 주소를 실행합니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth2/token/refresh?refreshToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiOTkxMDExNjktZmVjYS00NWUxLTliZTgtYmZjYzZiYjM0Yjg4IiwiZXhwIjoxNTU2MTQ1NDUyLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiODZhMDliYjctMzA2NS00NGQ5LWIxYjEtNWJlOGFlMjdlOWZkIiwiY2xpZW50X2lkIjoidGVzdENsaWVudElkIn0.fL51VTaLMHEf89Ao41nUrW-MzaNGBupg_4Us5nEtL_4">http://localhost:8081/oauth2/token/refresh?refreshToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiOTkxMDExNjktZmVjYS00NWUxLTliZTgtYmZjYzZiYjM0Yjg4IiwiZXhwIjoxNTU2MTQ1NDUyLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiODZhMDliYjctMzA2NS00NGQ5LWIxYjEtNWJlOGFlMjdlOWZkIiwiY2xpZW50X2lkIjoidGVzdENsaWVudElkIn0.fL51VTaLMHEf89Ao41nUrW-MzaNGBupg_4Us5nEtL_4</a></p>



<p class="wp-block-paragraph">실행 결과를 보면 access_token값이 갱신된 것을 확인할 수 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTYxMzI1NzgsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImJiMTI2Yzc4LTlkZTUtNDYzMC1hMjU4LTcwNzg4M2I1Nzg2ZiIsImNsaWVudF9pZCI6InRlc3RDbGllbnRJZCIsInNjb3BlIjpbInJlYWQiXX0.nLufRLebdxuc4GqMVoVHauesY4hQYeq5kCQtipKUEak",
"token_type":"bearer",
"refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiYmIxMjZjNzgtOWRlNS00NjMwLWEyNTgtNzA3ODgzYjU3ODZmIiwiZXhwIjoxNTU2MTQ1NDUyLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiODZhMDliYjctMzA2NS00NGQ5LWIxYjEtNWJlOGFlMjdlOWZkIiwiY2xpZW50X2lkIjoidGVzdENsaWVudElkIn0.axgvpcBksFqhyPyfJmfGFItNGFS3FqCGogsVqpSvZ60",
"expires_in":35999,
"scope":"read"
}</pre>



<h2 class="wp-block-heading">[내용 추가] Second App 클라이언트 등록 및 인증 처리 방법</h2>



<p class="wp-block-paragraph">테스트에서 사용한 test app에 이어 두번째 클라이언트를 등록합니다. 유저가 로그인 후 해당 app에 연결하여 token을 얻기위해 다음 작업을 진행합니다.</p>



<h3 class="wp-block-heading">oauth_client_detail에 신규 클라이언트 추가</h3>



<ul class="wp-block-list"><li>client_id / secret 암호화 한 값을 DB에 입력합니다.</li><li> secondapp / secondsecret 암호화 -> {bcrypt}$2a$10$A9pj3UFTItSr9ujk5eYuPOvlxzAsm4Y1p3rBWAkwU1rNayBVbmtu2</li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">insert into oauth_client_details(client_id, resource_ids,client_secret,scope,authorized_grant_types,web_server_redirect_uri,authorities,access_token_validity,refresh_token_validity,additional_information,autoapprove)
values('secondapp',null,'{bcrypt}$2a$10$A9pj3UFTItSr9ujk5eYuPOvlxzAsm4Y1p3rBWAkwU1rNayBVbmtu2','read,write','authorization_code,refresh_token','http://localhost:8081/oauth2/secondapp/callback','ROLE_USER',36000,50000,null,null);
</pre>



<h3 class="wp-block-heading">secondapp용 endpoint url 추가</h3>



<p class="wp-block-paragraph">Oauth2Controller.java와 내용이 같은 Controller를 하나 생성합니다. 변경 사항은 총 5군데이며 소스에 주석으로 표시하였습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@RequiredArgsConstructor
@RestController
@RequestMapping("/oauth2")
public class Oauth2SecondAppController {

    private final Gson gson;
    private final RestTemplate restTemplate;

    @GetMapping(value = "/secondapp/callback") // 1. endpoint 주소 수정
    public OAuthToken callbackSocial(@RequestParam String code) {

        String credentials = "secondapp:secondsecret"; // 2. credentials 정보 수정
        String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Authorization", "Basic " + encodedCredentials);

        MultiValueMap&lt;String, String> params = new LinkedMultiValueMap&lt;>();
        params.add("code", code);
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://localhost:8081/oauth2/secondapp/callback"); // 3. redirect_uri 정보 수정
        HttpEntity&lt;MultiValueMap&lt;String, String>> request = new HttpEntity&lt;>(params, headers);
        ResponseEntity&lt;String> response = restTemplate.postForEntity("http://localhost:8081/oauth/token", request, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return gson.fromJson(response.getBody(), OAuthToken.class);
        }
        return null;
    }

    @GetMapping(value = "/secondapp/token/refresh") // 4. endpoint 주소 수정
    public OAuthToken refreshToken(@RequestParam String refreshToken) {

        String credentials = "secondapp:secondsecret"; // 5. credentials 정보 수정
        String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Authorization", "Basic " + encodedCredentials);

        MultiValueMap&lt;String, String> params = new LinkedMultiValueMap&lt;>();
        params.add("refresh_token", refreshToken);
        params.add("grant_type", "refresh_token");
        HttpEntity&lt;MultiValueMap&lt;String, String>> request = new HttpEntity&lt;>(params, headers);
        ResponseEntity&lt;String> response = restTemplate.postForEntity("http://localhost:8081/oauth/token", request, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return gson.fromJson(response.getBody(), OAuthToken.class);
        }
        return null;
    }
}</pre>



<h3 class="wp-block-heading">신규 app으로 로그인</h3>



<p class="wp-block-paragraph">client_id, redirect_uri를 새로 등록한 정보에 맞게 수정하여 페이지를 호출합니다.</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=secondapp&amp;redirect_uri=http://localhost:8081/oauth2/secondapp/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=secondapp&amp;redirect_uri=http://localhost:8081/oauth2/secondapp/callback&amp;response_type=code&amp;scope=read</a></p>



<p class="wp-block-paragraph">로그인이 정상적으로 수행되면 아래와 같이 secondapp을 승인하겠냐는 물음 화면이 출력됩니다.</p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2021/03/login.png" alt="" class="wp-image-14822" width="593" height="224" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2021/03/login.png 791w, https://www.daddyprogrammer.org/wp-content/uploads/2021/03/login-768x290.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2021/03/login-150x57.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2021/03/login-300x113.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2021/03/login-696x263.png 696w" sizes="auto, (max-width: 593px) 100vw, 593px" /></figure>



<p class="wp-block-paragraph">Authorize를 클릭하면 secondapp의 token이 발급됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTUyNTYyNjUsInVzZXJfbmFtZSI6ImhhcHB5ZGFkZHlAZ21haWwuY29tIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImQzNWI2YTViLWUzMDQtNDYwNS04MzJkLTgwMzgyNmZlMTZmOSIsImNsaWVudF9pZCI6InNlY29uZGFwcCIsInNjb3BlIjpbInJlYWQiXX0.UetKc6wtv1LxB0IaZj1_OKqPs7ipfcPcGwAQ04XlMTNgkjUSJi6ttW0zc4N2BXKRuBRukGlWVqwhwzRHsKXAw2N6uwYMGzLHTfAfaTmySd8tXJeR7kMdOXd4diZ7Ex-lcyuMWZRkhNwlyWbz5nxC-ilu9TpkQ0ZCFxjti07GluSTsu-AjLKvC-x6zAkBtU0aV6VeYJ-PE97gcr8J7tjw6neP3UbyhLkbmuCqtFpCpDZHrgCeV2IlLKlp6OpPWcPPna9BxPIojE4SkXp_mLcbUxM9PnNN1xqMNg2aI2LOFPOS5CEw82Lv_cyRuuFsk8MEKIm9tVX8rwLKgDlYyhyc2Q","token_type":"bearer","refresh_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJoYXBweWRhZGR5QGdtYWlsLmNvbSIsInNjb3BlIjpbInJlYWQiXSwiYXRpIjoiZDM1YjZhNWItZTMwNC00NjA1LTgzMmQtODAzODI2ZmUxNmY5IiwiZXhwIjoxNjE1MjcwMjY1LCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiMjUxMmNmMjctYzU2MS00NDc0LTgyYmMtMTI1YmVjMTY5ZDQ2IiwiY2xpZW50X2lkIjoic2Vjb25kYXBwIn0.K56TjqE3g7VgnDd_dusC4gK6xcVjJzGKq0ohe7nx9HtUk3rQMFMUHEKhegbpfntH8Lp-4TPIdjmV1PG4bUIXuXQzMnyoqu3oZD4YqYtLM_RndeUSKeMq-g44dSkyiV6BPyvgtWFKQJkr_O3Jye_PYd3FP00M-eCMJSv2irJrdEjNwaFrMIn9GkwpHx2KvNJ-JQYw6SZLqHOVmljOhwJKCXGOR06ZwP4-zRGrvmFrIdsk9iTI7CJxs7BOdx455ttheKogdIctNKqvllgEpRzp9q111w5oyyhr0TFtaNehUgyd9ZvBVEzpN8GwrAnksD85k5bwTGTv1JiSTvniMIdWLw","expires_in":35999,"scope":"read"}</pre>
<p>The post <a href="https://www.daddyprogrammer.org/post/1287/spring-oauth2-authorizationserver-database/">Spring Boot Oauth2 &#8211; AuthorizationServer : DB처리, JWT 토큰 방식 적용</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/1287/spring-oauth2-authorizationserver-database/feed/</wfw:commentRss>
			<slash:comments>42</slash:comments>
		
		
		
		<series:name><![CDATA[SpringBoot2로 Oauth2 서버 만들기]]></series:name>
	</item>
		<item>
		<title>Spring Boot Oauth2 &#8211; AuthorizationServer</title>
		<link>https://www.daddyprogrammer.org/post/1239/spring-oauth-authorizationserver/</link>
					<comments>https://www.daddyprogrammer.org/post/1239/spring-oauth-authorizationserver/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Tue, 23 Apr 2019 01:03:39 +0000</pubDate>
				<category><![CDATA[Oauth2]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Authorization]]></category>
		<category><![CDATA[AuthorizationServer]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=1239</guid>

					<description><![CDATA[<p>Spring 프레임웍에서 제공하는 Oauth2 프로젝트를 이용하여 Oauth Authorization Server를 구축해 보겠습니다. Oauth Authorization은 클라이언트가 서비스 제공자로부터 회원 리소스를 제공받기 위해 인증 및 권한 부여를 받는 일련의 절차라고 보면 됩니다. 이를테면 페이스북이나, 구글, 카카오톡 등이 대표적인 서비스 제공자인데요. 해당 서비스에 로그인하고 제휴한 앱에 회원정보 접근을 승인하는 과정을 제공하는 것이 Authorization 서버입니다. 즉 이번에 실습하는 것은 클라이언트가 [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1239/spring-oauth-authorizationserver/">Spring Boot Oauth2 &#8211; AuthorizationServer</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Spring 프레임웍에서 제공하는 Oauth2 프로젝트를 이용하여 Oauth Authorization Server를 구축해 보겠습니다. Oauth Authorization은 클라이언트가 서비스 제공자로부터 회원 리소스를 제공받기 위해 인증 및 권한 부여를 받는 일련의 절차라고 보면 됩니다.</p>



<p class="wp-block-paragraph">이를테면 페이스북이나, 구글, 카카오톡 등이 대표적인 서비스 제공자인데요. 해당 서비스에 로그인하고 제휴한 앱에 회원정보 접근을 승인하는 과정을 제공하는 것이 Authorization 서버입니다.</p>



<p class="wp-block-paragraph">즉 이번에 실습하는 것은 클라이언트가 아니라, 페이스북 같은 서비스 제공자를 만들어보는 실습이라고 보면 됩니다.</p>



<p class="wp-block-paragraph">authorization 서버의 인증 타입은 총 4가지가 있으며, authorization_code 타입이 가장 대중적으로 이용됩니다. 아래는 authorization_code 타입 인증의 대략적인 Flow입니다. 아래 내용 중 로그인은 Authenticaion이라 하고 로그인 후 회원의 리소스를 접근할 수 있도록 권한을 부여받는 것을 Authorization+AccessControl 이라고 합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4.jpeg" alt="" class="wp-image-1497" width="600" height="395" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4.jpeg 1200w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-1024x673.jpeg 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-768x505.jpeg 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-150x99.jpeg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-300x197.jpeg 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-696x458.jpeg 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-oauth2-4-639x420.jpeg 639w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>



<p class="wp-block-paragraph"><span class="has-inline-color has-vivid-cyan-blue-color"><strong>최신 소스는 아래 GitHub 주소를 참고해 주세요.<br> <a rel="noreferrer noopener" aria-label=" (새탭으로 열기)" href="https://github.com/codej99/SpringOauth2AuthorizationServer.git" target="_blank">https://github.com/codej99/SpringOauth2AuthorizationServer.git</a></strong></span></p>



<h3 class="wp-block-heading">Spring gradle 프로젝트 생성</h3>



<p class="wp-block-paragraph">프로젝트 초기 세팅은 아래 링크를 참고하시면 됩니다.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="rKiHdJH5F4"><a href="https://www.daddyprogrammer.org/post/19/spring-boot2-start-intellij/">SpringBoot2로 Rest api 만들기(1) &#8211;  Intellij Community 프로젝트생성</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;SpringBoot2로 Rest api 만들기(1) &#8211;  Intellij Community 프로젝트생성&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/19/spring-boot2-start-intellij/embed/#?secret=pT9YpH3IK1#?secret=rKiHdJH5F4" data-secret="rKiHdJH5F4" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p class="wp-block-paragraph">신규 프로젝트를 초기 구성하는데 어려움이 있다면 Spring initializr를 통해 간편하게 프로젝트를 생성할 수 있습니다. 다음 포스팅을 참고해 주세요.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="BU4AyAaqUE"><a href="https://www.daddyprogrammer.org/post/1212/springboot2-create-by-spring-initializr/">Spring initializr로 Spring 프로젝트 생성하기</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Spring initializr로 Spring 프로젝트 생성하기&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/1212/springboot2-create-by-spring-initializr/embed/#?secret=Mue10cQpqO#?secret=BU4AyAaqUE" data-secret="BU4AyAaqUE" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p class="wp-block-paragraph">향후 DB연동을 위해 사용할 H2에 대한 내용은 아래 포스팅을 참고해주십시오.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="dOO6QjNTH4"><a href="https://www.daddyprogrammer.org/post/152/spring-boot2-h2-database-intergrate/">SpringBoot2로 Rest api 만들기(3) – H2 Database 연동</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;SpringBoot2로 Rest api 만들기(3) – H2 Database 연동&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/152/spring-boot2-h2-database-intergrate/embed/#?secret=bKeJ27INT6#?secret=dOO6QjNTH4" data-secret="dOO6QjNTH4" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h3 class="wp-block-heading">gradle.build 내용 수정</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plugins {
    id 'org.springframework.boot' version '2.1.4.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.rest'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-security:2.1.2.RELEASE'
    implementation 'org.springframework.cloud:spring-cloud-starter-oauth2:2.1.2.RELEASE'
    implementation 'com.google.code.gson:gson'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}</pre>



<h3 class="wp-block-heading">Authorization Server Config 생성</h3>



<p class="wp-block-paragraph">Oauth2AuthorizationConfig를 생성하고 아래 어노테이션을 붙여서 인증 서버를 활성화 합니다.</p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">@Configuration<br>@EnableAuthorizationServer</span></strong></p>



<p class="wp-block-paragraph">클라이언트 정보는 테스트를 위해 일단 더미 데이터를 세팅하겠습니다.</p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">redirectUri</span></strong><br>인증 완료 후 이동할 클라이언트 웹 페이지 주소로 code 값을 실어서 보내줍니다.</p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">authorizedGrantTypes</span></strong><br>인증 방식은 총 4가지가 있습니다. 그중 authorization_code 방식이 주로 사용됩니다.</p>



<figure class="wp-block-table"><table><tbody><tr><td><span class="has-inline-color has-luminous-vivid-orange-color"><strong>Authorization Code</strong> </span></td><td>가장 대중적인 방식. <br>Service Provider가 제공하는 인증 화면에 로그인하고 <br>클라이언트 앱이 요청하는 리소스 접근 요청을 승인하면, <br>지정한 redirect_uri로 code를 넘겨주는데. 해당 code로 <br>access_token을 얻는다. </td></tr><tr><td><strong><span class="has-inline-color has-luminous-vivid-orange-color">Implicit </span></strong></td><td>Authorization Code와 flow가 비슷하다. <br>인증 후 redirect_uri로 직접 access_token을 전달받으므로. <br>전체 프로세스는 좀 더 간단해지지만 Authorization Code <br>방식에 비해 보안성은 떨어진다. </td></tr><tr><td><span class="has-inline-color has-luminous-vivid-orange-color"><strong>password credential</strong> </span></td><td>Resource&nbsp;Owner가&nbsp;직접&nbsp;Client에&nbsp;아이디와&nbsp;패스워드를&nbsp;입력하고<br>Authorization&nbsp;서버에&nbsp;해당&nbsp;정보로&nbsp;인증받아&nbsp;access_token을&nbsp;직접<br>얻어오는&nbsp;방식.<br>access&nbsp;token을&nbsp;얻어올 때&nbsp;Client에&nbsp;아이디&nbsp;패스워드가&nbsp;노출되어<br>보안이&nbsp;떨어지므로&nbsp;일반적으로&nbsp;공식&nbsp;애플리케이션에서만&nbsp;사용한다.</td></tr><tr><td> <br><strong><span class="has-inline-color has-luminous-vivid-orange-color">client credential</span></strong> </td><td>access_token을 얻는데 정해진 인증 key(secret)로 요청하며, <br>일반적인 사용보다는 server 간 통신을 할 때 사용한다. </td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">scopes</span></strong><br>인증 후 얻은 accessToken으로 접근할 수 있는 리소스의 범위입니다. 테스트로 read, write scope가 있다고 세팅 합니다. resource서버(api서버)에서는 해당 scope정보로 클라이언트에게 제공할 리소스를 제한하거나 노출시킵니다.</p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">accessTokenValiditySeconds</span></strong><br>발급된 accessToken의 유효시간(초) 입니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Configuration
@EnableAuthorizationServer
public class Oauth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("testClientId")
                .secret("testSecret")
                .redirectUris("http://localhost:8081/oauth2/callback")
                .authorizedGrantTypes("authorization_code")
                .scopes("read", "write")
                .accessTokenValiditySeconds(30000);
    }
}</pre>



<h3 class="wp-block-heading">SpringSecurity Config 생성<br></h3>



<p class="wp-block-paragraph">config 패키지 하위에 SpringSecurityConfig를 작성합니다.</p>



<p class="wp-block-paragraph">password세팅 시에는 암호화에 대한 준비가 아직 되어있지 않으므로 NoOpPasswordEncoder를 사용하도록 세팅합니다. 인증할 회원 정보도 테스트를 위해 일단 더미로 세팅합니다. csrf는 사용 안 함 처리합니다.<br>.headers().frameOptions().disable()은 security 적용 시 h2 console 사용이 막히므로 세팅합니다. oauth로 시작하는 리소스는 authorization 서버 세팅시 자동으로 생성되는 주소를 누구나 접근할 수 있게 하기 위한 세팅입니다. callback테스트를 위한 url과 h2 console용 주소도 모두 접근 가능하도록 세팅합니다. security 로그인 화면은 일단 기본 폼을 사용하도록 세팅합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder noOpPasswordEncoder() {
      return NoOpPasswordEncoder.getInstance();
    }

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

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .csrf().disable()
                .headers().frameOptions().disable()
                .and()
                .authorizeRequests().antMatchers("/oauth/**", "/oauth2/callback", "/h2-console/*").permitAll()
                .and()
                .formLogin().and()
                .httpBasic();
    }
}</pre>



<h3 class="wp-block-heading">공통 환경 세팅을 위한 WebMvcConfig 생성</h3>



<p class="wp-block-paragraph">config 패키지 하위에 WebMvcConfig를 생성하고 프로젝트에서 사용하는 공통 빈이나 필요한 환경 정보를 세팅합니다. 아래에서는 인증서버에 크로스 도메인 접근 가능하도록 cors 설정을 추가하였습니다. 그 외 Restemplate이나 PasswordEncoder 등 프로젝트 전반적으로 사용되는 모듈에 대한 Bean 설정을 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.config;

// import 생략

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final long MAX_AGE_SECONDS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(MAX_AGE_SECONDS);
    }

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}</pre>



<h3 class="wp-block-heading">application.yml 작성</h3>



<p class="wp-block-paragraph">향후 개발할 리소스 서버(api서버)와 구분을 두기 위해 8081로 세팅합니다.<br>나머지는 h2와 jpa설정입니다. 테스트 환경이나 기호에 맞게 변경해 사용하면 됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">server:
  port: 8081
spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
  datasource:
    url: jdbc:h2:tcp://localhost/~/test
    driver-class-name: org.h2.Driver
    username: sa
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    properties.hibernate.hbm2ddl.auto: update
    showSql: true</pre>



<h3 class="wp-block-heading">1차 테스트</h3>



<p class="wp-block-paragraph">위에서 세팅한 테스트 클라이언트, 테스트 회원으로 다음과 같이 인증 url을 브라우저에서 호출합니다. authorization_code 인증 방식은 로그인이 완료되었을 때 인증 코드를 주는 방식 이므로 로그인이 되어있지 않은 경우 로그인 화면으로 리다이렉트 됩니다.(SpringSecurity에서 기본으로 제공하는 화면이며 커스텀하게 UI 변경 가능합니다.)</p>



<p class="wp-block-paragraph"><a href="http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read">http://localhost:8081/oauth/authorize?client_id=testClientId&amp;redirect_uri=http://localhost:8081/oauth2/callback&amp;response_type=code&amp;scope=read</a></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1.png" alt="" class="wp-image-1257" width="330" height="231" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1.png 660w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1-150x105.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1-300x210.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1-600x420.png 600w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_1-100x70.png 100w" sizes="auto, (max-width: 330px) 100vw, 330px" /></figure>



<p class="wp-block-paragraph">로그인에 성공하면 클라이언트의 리소스 허용 확인을 묻는 화면으로 이동합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2.png" alt="" class="wp-image-1258" width="501" height="186" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2.png 1002w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-768x285.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-150x56.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-300x111.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_2-696x258.png 696w" sizes="auto, (max-width: 501px) 100vw, 501px" /></figure>



<p class="wp-block-paragraph">리소스 사용을 허용하면 테스트로 세팅한 redirectUri로 리다이렉트 됩니다. 현재는 받아줄 controller를 세팅하지 않았으므로 404 화면이 뜨게 됩니다. 여기서 봐야 될 중요한 점은 주소 마지막에 추가로 넘어온 code값입니다.<span class="has-inline-color has-vivid-red-color"> <strong>code=KltwEm</strong></span><br>authrization_code를 통한 승인 방식은 완료 후에 리다이렉트 주소로 code를 실어 보내주는데 해당 code값으로 api를 호출하여 accessToken을 얻을 수 있습니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_3.png" alt="" class="wp-image-1263" width="495" height="159" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_3.png 660w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_3-150x48.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/oauth_3-300x96.png 300w" sizes="auto, (max-width: 495px) 100vw, 495px" /></figure>



<h2 class="wp-block-heading">토큰 정보를 받을 수 있도록 개선</h2>



<h3 class="wp-block-heading">build.gradle에 gson 라이브러리 추가</h3>



<p class="wp-block-paragraph">Json String을 Java 객체로 맵핑하기 위해 Gson 라이브러리를 추가합니다. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">implementation 'com.google.code.gson:gson'</pre>



<h3 class="wp-block-heading">토큰정보를 받을 모델 생성</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.oauth2.model.oauth2;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class OAuthToken {
    private String access_token;
    private String token_type;
    private String refresh_token;
    private long expires_in;
    private String scope;
}</pre>



<h3 class="wp-block-heading">토큰 생성을 확인하기 위한 redirect 주소 처리Controller 생성</h3>



<p class="wp-block-paragraph">controller.common package 아래에 Oauth2Controller 생성합니다. 이 Controller는 Oauth인증 완료 후 redirectUri를 처리해주기 위한 Controller로 원래는 해당 프로젝트가 아닌 클라이언트에 세팅되는 화면이 되어야 합니다. 하지만 인증서버 테스트 결과를 보기 위해서 임시로 만든 것입니다. curl 방식으로 다음과 같이 호출하여 결과를 볼 수도 있습니다. <br>기본적으로 토큰 요청 시 Header에 Authorization:Basic으로 clientId와 secret값을 인코딩해서 넣어야 하므로 생각보다 복잡합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ curl -X POST \
'http://localhost:8081/oauth/token' \
-H 'Authorization:Basic dGVzdENsaWVudElkOnRlc3RTZWNyZXQ=' \
-d 'grant_type=authorization_code' \
-d 'code=u6q9Ju' \
-d 'redirect_uri=http://localhost:8081/oauth2/callback'</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@RequiredArgsConstructor
@RestController
@RequestMapping("/oauth2")
public class Oauth2Controller {

    private final Gson gson;
    private final RestTemplate restTemplate;

    @GetMapping(value = "/callback")
    public OAuthToken callbackSocial(@RequestParam String code) {

        String credentials = "testClientId:testSecret";
        String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization", "Basic " + encodedCredentials);

        MultiValueMap&lt;String, String> params = new LinkedMultiValueMap&lt;>();
        params.add("code", code);
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://localhost:8081/oauth2/callback");
        HttpEntity&lt;MultiValueMap&lt;String, String>> request = new HttpEntity&lt;>(params, headers);
        ResponseEntity&lt;String> response = restTemplate.postForEntity("http://localhost:8081/oauth/token", request, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return gson.fromJson(response.getBody(), OAuthToken.class);
        }
        return null;
    }
}</pre>



<h3 class="wp-block-heading">2차 테스트</h3>



<p class="wp-block-paragraph">1차와 동일한 url을 호출하여 인증 완료되면 이번에는 404 화면이 뜨지 않고 다음과 같은 결과를 볼 수 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "access_token":"5bf1b64e-d0fa-4f47-b747-aee27cf1dc0a",
    "token_type":"bearer",
    "refresh_token":null,
    "expires_in":29974,
    "scope":"read"
}</pre>



<p class="wp-block-paragraph">여기까지 간단하게 인증서버를 구축하여 Access Token을 얻는 것까지 실습을 진행해 보았습니다. 리소스 서버에 요청시 Access Token을 실어 보내면 해당 리소스 정보를 조회하거나 수정할 수 있습니다. </p>
<p>The post <a href="https://www.daddyprogrammer.org/post/1239/spring-oauth-authorizationserver/">Spring Boot Oauth2 &#8211; AuthorizationServer</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/1239/spring-oauth-authorizationserver/feed/</wfw:commentRss>
			<slash:comments>21</slash:comments>
		
		
		
		<series:name><![CDATA[SpringBoot2로 Oauth2 서버 만들기]]></series:name>
	</item>
		<item>
		<title>SpringBoot2로 Rest api 만들기(8) –  SpringSecurity 를 이용한 인증 및 권한부여</title>
		<link>https://www.daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/</link>
					<comments>https://www.daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Mon, 15 Apr 2019 14:34:20 +0000</pubDate>
				<category><![CDATA[SpringSecurity]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[SpringBoot]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Authorization]]></category>
		<category><![CDATA[JWT]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=636</guid>

					<description><![CDATA[<p>이번 시간에는 SpringSecurity를 이용하여 api 서버의 사용 권한을 제한하는 방법에 대해 알아보도록 하겠습니다. 지금까지 개발한 api는 권한 부여 기능이 없어 누구나 회원 정보를 조회, 생성 및 수정, 삭제를 할 수 있었습니다. 이 상태로 api를 서비스에 내보낸다면 많은 문제가 발생할 것은 불을 보듯 뻔한 일입니다. 이러한 문제를 해결하기 위해 인증한 회원만 api를 사용할 수 있도록 개선해 [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/">SpringBoot2로 Rest api 만들기(8) –  SpringSecurity 를 이용한 인증 및 권한부여</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">이번 시간에는 SpringSecurity를 이용하여 api 서버의 사용 권한을 제한하는 방법에 대해 알아보도록 하겠습니다. 지금까지 개발한 api는 권한 부여 기능이 없어 누구나 회원 정보를 조회, 생성 및 수정, 삭제를 할 수 있었습니다. 이 상태로 api를 서비스에 내보낸다면 많은 문제가 발생할 것은 불을 보듯 뻔한 일입니다. 이러한 문제를 해결하기 위해 인증한 회원만 api를 사용할 수 있도록 개선해 보겠습니다.</p>



<h3 class="wp-block-heading">SpringSecurity</h3>



<p class="wp-block-paragraph">스프링에서는 인증 및 권한 부여를 통해 리소스의 사용을 쉽게 컨트롤할 수 있는 SpringSecurity  framework를 제공하고 있습니다. Spring boot기반의 프로젝트에 SpringSecurity를 적용하면 보안 관련 처리를 자체적으로 구현할 필요 없이 쉽게 필요한 기능을 구현할 수 있습니다. 간략하게 아래의 그림처럼 SpringSecurity는 Spring의 DispatcherServlet 앞단에 Filter를 등록시켜 요청을 가로챕니다. 클라이언트에게 리소스 접근 권한이 없을 경우엔 인증(ex:로그인) 화면으로 자동으로 리다이렉트 합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1.jpeg" alt="" class="wp-image-1141" width="770" height="308" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1.jpeg 1539w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-1024x409.jpeg 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-768x307.jpeg 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-1536x614.jpeg 1536w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-150x60.jpeg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-300x120.jpeg 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-696x278.jpeg 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_3-1-1051x420.jpeg 1051w" sizes="auto, (max-width: 770px) 100vw, 770px" /></figure>



<h3 class="wp-block-heading">SpringSecurity Filter</h3>



<p class="wp-block-paragraph">SpringSecurity는 기능별 필터의 집합으로 되어있고 필터의 처리 순서는 아래와 같습니다. 종류가 매우 많지만 여기서 중요한 것은 필터의 처리 순서입니다. 클라이언트가 리소스를 요청할 때 접근 권한이 없는 경우 기본적으로 로그인 폼으로 보내게 되는데 그 역할을 하는 필터는 <span class="has-inline-color has-luminous-vivid-orange-color"><strong>UsernamePasswordAuthenticationFilter</strong></span>입니다.<br>Rest Api에서는 로그인 폼이 따로 없으므로 인증 권한이 없다는 오류 Json을 내려줘야 하므로  <br><span class="has-inline-color has-luminous-vivid-orange-color"><strong>UsernamePasswordAuthenticationFilter </strong></span>전에 관련 처리를 넣어야 함을 알 수 있습니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1.jpeg" alt="" class="wp-image-1143" width="616" height="533" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1.jpeg 1231w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-1024x887.jpeg 1024w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-768x665.jpeg 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-150x130.jpeg 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-300x260.jpeg 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-696x603.jpeg 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-485x420.jpeg 485w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/SpringSecurity-security_4-1-534x462.jpeg 534w" sizes="auto, (max-width: 616px) 100vw, 616px" /></figure>



<ol class="wp-block-list"><li> ChannelProcessingFilter</li><li> SecurityContextPersistenceFilter</li><li> ConcurrentSessionFilter</li><li> HeaderWriterFilter</li><li> CsrfFilter</li><li> LogoutFilter</li><li> X509AuthenticationFilter</li><li> AbstractPreAuthenticatedProcessingFilter</li><li> CasAuthenticationFilter</li><li><span class="has-inline-color has-vivid-red-color"> </span><strong><span class="has-inline-color has-luminous-vivid-orange-color">UsernamePasswordAuthenticationFilter</span></strong></li><li> BasicAuthenticationFilter</li><li> SecurityContextHolderAwareRequestFilter</li><li> JaasApiIntegrationFilter</li><li> RememberMeAuthenticationFilter</li><li> AnonymousAuthenticationFilter</li><li> SessionManagementFilter</li><li> ExceptionTranslationFilter</li><li> FilterSecurityInterceptor</li><li> SwitchUserFilter</li></ol>



<h3 class="wp-block-heading">API 인증 및 권한 부여, 제한된 리소스의 요청</h3>



<ul class="wp-block-list"><li>인증을 위해 가입(Signup)및 로그인(Signin) api를 구현합니다.</li><li>가입 시 제한된 리소스에 접근할 수 있는 ROLE_USER 권한을 회원에게 부여합니다. </li><li>SpringSecurity 설정에는 접근 제한이 필요한 리소스에 대해서 ROLE_USER 권한을 가져야 접근 가능하도록 세팅합니다. </li><li>권한을 가진 회원이 로그인 성공 시엔 리소스에 접근할 수 있는 Jwt 보안 토큰을 발급합니다.</li><li>Jwt 보안 토큰으로 회원은 권한이 필요한 api 리소스를 요청하여 사용합니다.</li></ul>



<h3 class="wp-block-heading">JWT 란? </h3>



<p class="wp-block-paragraph">JSON Web Token (JWT)은 JSON 객체로서 당사자간에 안전하게 정보를 전송할 수 있는 작고 독립적인 방법을 정의하는 공개 표준 (RFC 7519)입니다. 자세한 내용은 아래 링크에서 확인할 수 있습니다.<br><a rel="noreferrer noopener" aria-label=" (새탭으로 열기)" href="https://jwt.io/introduction/" target="_blank">https://jwt.io/introduction/</a><br>Jwt는 JSON 객체를 암호화하여 만든 String값으로 기본적으로 암호화되어있어 변조하기가 어려운 정보입니다. 또한 다른 토큰과 달리 토큰 자체에 데이터를 가지고 있습니다. api 서버에서는 로그인이 완료된 클라이언트에게 회원을 구분할 수 있는 값을 넣은 Jwt 토큰을 생성하여 발급하고, 클라이언트는 이 Jwt 토큰을 이용하여 권한이 필요한 리소스를 서버에 요청하는 데 사용할 수 있습니다. api서버는 클라이언트에게서 전달받은 Jwt 토큰이 유효한지 확인하고 담겨있는 회원 정보를 확인하여 제한된 리소스를 제공하는데 이용할 수 있습니다. </p>



<h3 class="wp-block-heading">build.gradle에 library 추가</h3>



<p class="wp-block-paragraph">SpringSecurity 및 Jwt관련 라이브러리를 build.gradle에 추가합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt:0.9.1'</pre>



<h3 class="wp-block-heading"> JwtTokenProvider 생성</h3>



<p class="wp-block-paragraph"> Jwt 토큰 생성 및 유효성 검증을 하는 컴포넌트입니다. Jwt는 여러 가지 암호화 알고리즘을 제공하며 알고리즘(SignatureAlgorithm.XXXXX)과 비밀키(secretKey)를 가지고 토큰을 생성하게 됩니다. 이때 claim정보에는 토큰에 부가적으로 실어 보낼 정보를 세팅할 수 있습니다. claim 정보에 회원을 구분할 수 있는 값을 세팅하였다가 토큰이 들어오면 해당 값으로 회원을 구분하여 리소스를 제공하면 됩니다. 그리고 Jwt토큰에는 expire 시간을 세팅할 수 있습니다. 토큰 발급 후 일정 시간 이후에는 토큰을 만료시키는 데 사용할 수 있습니다. resolveToken 메서드는 Http request header에 세팅된 토큰 값을 가져와 유효성을 체크합니다. 제한된 리소스를 요청할 때 Http header에 토큰을 세팅하여 호출하면 유효성을 검증하여 사용자 인증을 할 수 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.config.security;

// import 생략

@RequiredArgsConstructor
@Component
public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈

    @Value("spring.jwt.secret")
    private String secretKey;

    private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효

    private final UserDetailsService userDetailsService;

    @PostConstruct
    protected void init() {
        secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
    }

    // Jwt 토큰 생성
    public String createToken(String userPk, List&lt;String> roles) {
        Claims claims = Jwts.claims().setSubject(userPk);
        claims.put("roles", roles);
        Date now = new Date();
        return Jwts.builder()
                .setClaims(claims) // 데이터
                .setIssuedAt(now) // 토큰 발행일자
                .setExpiration(new Date(now.getTime() + tokenValidMilisecond)) // set Expire Time
                .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘, secret값 세팅
                .compact();
    }

    // Jwt 토큰으로 인증 정보를 조회
    public Authentication getAuthentication(String token) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
        return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
    }

    // Jwt 토큰에서 회원 구별 정보 추출
    public String getUserPk(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
    }

    // Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"
    public String resolveToken(HttpServletRequest req) {
        return req.getHeader("X-AUTH-TOKEN");
    }

    // Jwt 토큰의 유효성 + 만료일자 확인
    public boolean validateToken(String jwtToken) {
        try {
            Jws&lt;Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
            return !claims.getBody().getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/test
    driver-class-name: org.h2.Driver
    username: sa
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    properties.hibernate.hbm2ddl.auto: update
    showSql: true
  messages:
    basename: i18n/exception
    encoding: UTF-8
  jwt:
    secret: govlepel@$&amp;</pre>



<h3 class="wp-block-heading">JwtAuthenticationFilter 생성 </h3>



<p class="wp-block-paragraph">Jwt가 유효한 토큰인지 인증하기 위한 Filter입니다. com.rest.api.config.security 하위에 Class를 생성합니다. 이 필터는 Security 설정 시 UsernamePasswordAuthenticationFilter앞에 세팅할 것입니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.config.security;

// import 생략

public class JwtAuthenticationFilter extends GenericFilterBean {

    private JwtTokenProvider jwtTokenProvider;

    // Jwt Provier 주입
    public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    // Request로 들어오는 Jwt Token의 유효성을 검증(jwtTokenProvider.validateToken)하는 filter를 filterChain에 등록합니다.
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);
        if (token != null &amp;&amp; jwtTokenProvider.validateToken(token)) {
            Authentication auth = jwtTokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(request, response);
    }
}</pre>



<h3 class="wp-block-heading">SpringSecurity Configuration</h3>



<p class="wp-block-paragraph">서버에 보안 설정을 적용합니다. com.rest.api.config.security 하위에 다음 Class를 작성합니다. 아무나 접근 가능한 리소스는 permitAll()로 세팅하고 나머지 리소스는 다음과 같이 &#8216;ROLE_USER&#8217; 권한이 필요함으로 명시합니다. anyRequest().hasRole(&#8220;USER&#8221;) 또는 anyRequest().authenticated()는 동일한 동작을 합니다.<br>위에서 설명했듯이 해당 filter는 UsernamePasswordAuthenticationFilter 앞에 설정해야 합니다. SpringSecurity 적용 후에는 모든 리소스에 대한 접근이 제한되므로. Swagger 페이지에 대해서는 예외를 적용해야 페이지에 접근할 수 있습니다. 리소스 접근 제한 표현식은 여러 가지가 있으며 다음과 같습니다.</p>



<p class="wp-block-paragraph"><span class="has-inline-color has-vivid-cyan-blue-color"><strong>hasIpAddress(ip)</strong></span> &#8211; 접근자의 IP주소가 매칭 하는지 확인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><span class="has-inline-color has-vivid-cyan-blue-color"><strong>hasRole(role)</strong></span> &#8211; 역할이 부여된 권한(Granted Authority)과 일치하는지 확인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">hasAnyRole(role)</span></strong> &#8211; 부여된 역할 중 일치하는 항목이 있는지 확인합니다.<br>ex) access = &#8220;hasAnyRole(&#8216;ROLE_USER&#8217;,&#8217;ROLE_ADMIN&#8217;)&#8221; &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">permitAll</span></strong> &#8211; 모든 접근자를 항상 승인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">denyAll</span></strong> &#8211; 모든 사용자의 접근을 거부합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><span class="has-inline-color has-vivid-cyan-blue-color"><strong>anonymous </strong></span>&#8211; 사용자가 익명 사용자인지 확인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">authenticated </span></strong>&#8211; 인증된 사용자인지 확인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">rememberMe </span></strong>&#8211; 사용자가 remember me를 사용해 인증했는지 확인합니다. &nbsp; &nbsp; &nbsp; &nbsp; <br><strong><span class="has-inline-color has-vivid-cyan-blue-color">fullyAuthenticated </span></strong>&#8211; 사용자가 모든 크리덴셜을 갖춘 상태에서 인증했는지 확인합니다. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.config.security;

// import 생략

@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final JwtTokenProvider jwtTokenProvider;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증하므로 세션은 필요없으므로 생성안함.
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
                    .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣는다

    }

    @Override // ignore check swagger resource
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
                "/swagger-ui.html", "/webjars/**", "/swagger/**");

    }
}</pre>



<h3 class="wp-block-heading">Custom UserDetailsService 정의</h3>



<p class="wp-block-paragraph">토큰에 세팅된 유저 정보로 회원정보를 조회하는 UserDetailsService를 재정의 합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@RequiredArgsConstructor
@Service
public class CustomUserDetailService implements UserDetailsService {

    private final UserJpaRepo userJpaRepo;

    public UserDetails loadUserByUsername(String userPk) {
        return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
    }
}</pre>



<h3 class="wp-block-heading">User Entity 수정</h3>



<p class="wp-block-paragraph">SpringSecurity의 보안을 적용하기 위해 User entity에 UserDetails Class를 상속받아 추가 정보를 재정의 합니다. roles는 회원이 가지고 있는 권한 정보이고, 가입했을 때는 기본 &#8220;ROLE_USER&#8221;가 세팅됩니다. 권한은 회원당 여러 개가 세팅될 수 있으므로 Collection으로 선언합니다.<br>getUsername은 security에서 사용하는 회원 구분 id입니다. 여기선 uid로 변경합니다.<br>다음 값들은 Security에서 사용하는 회원 상태 값입니다. 여기선 모두 사용 안 하므로 true로 설정합니다.<br>Json결과로 출력 안 할 데이터는 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 어노테이션을 선언해줍니다.</p>



<p class="wp-block-paragraph"><span class="has-inline-color has-vivid-cyan-blue-color"><strong>isAccountNonExpired</strong> </span>&#8211;  계정이 만료가 안되었는지<br><span class="has-inline-color has-vivid-cyan-blue-color"><strong>isAccountNonLocked</strong> </span>&#8211; 계정이 잠기지 않았는지<br><span class="has-inline-color has-vivid-cyan-blue-color"><strong>isCredentialsNonExpired</strong> </span>&#8211; 계정 패스워드가 만료 안됬는지<br><span class="has-inline-color has-vivid-cyan-blue-color"><strong>isEnabled</strong> </span>&#8211; 계정이 사용 가능한지</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
    @Id // pk
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long msrl;
    @Column(nullable = false, unique = true, length = 30)
    private String uid;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(nullable = false, length = 100)
    private String password;
    @Column(nullable = false, length = 100)
    private String name;

    @ElementCollection(fetch = FetchType.EAGER)
    @Builder.Default
    private List&lt;String> roles = new ArrayList&lt;>();

    @Override
    public Collection&lt;? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public String getUsername() {
        return this.uid;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isEnabled() {
        return true;
    }
}</pre>



<h3 class="wp-block-heading">UserJpaRepo에 findByUid추가</h3>



<p class="wp-block-paragraph">회원 가입 시 가입한 이메일 조회를 위해 다음 메서드를 선언합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public interface UserJpaRepo extends JpaRepository&lt;User, Integer> {
    Optional&lt;User> findByUid(String email);
}</pre>



<h3 class="wp-block-heading">로그인 예외 추가 </h3>



<p class="wp-block-paragraph">CEmailSigninFailedException 생성</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class CEmailSigninFailedException extends RuntimeException {
    public CEmailSigninFailedException(String msg, Throwable t) {
        super(msg, t);
    }

    public CEmailSigninFailedException(String msg) {
        super(msg);
    }

    public CEmailSigninFailedException() {
        super();
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># exception_en.yml
emailSigninFailed:
  code: "-1001"
  msg: "Your account does not exist or your email or password is incorrect."
  
# exception_ko.yml
emailSigninFailed:
  code: "-1001"
  msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># ExceptionAdvice    
@ExceptionHandler(CEmailSigninFailedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected CommonResult emailSigninFailed(HttpServletRequest request, CEmailSigninFailedException e) {
        return responseService.getFailResult(Integer.valueOf(getMessage("emailSigninFailed.code")), getMessage("emailSigninFailed.msg"));
}</pre>



<h3 class="wp-block-heading">가입 / 로그인 Controller 추가 </h3>



<p class="wp-block-paragraph">로그인 성공 시에는 결과로 Jwt토큰을 발급합니다.<br>가입 시에는 패스워드 인코딩을 위해 passwordEncoder설정을 합니다. 기본 설정은 bcrypt encoding이 사용됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Api(tags = {"1. Sign"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class SignController {

    private final UserJpaRepo userJpaRepo;
    private final JwtTokenProvider jwtTokenProvider;
    private final ResponseService responseService;
    private final PasswordEncoder passwordEncoder;

    @ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
    @PostMapping(value = "/signin")
    public SingleResult&lt;String> signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
                                       @ApiParam(value = "비밀번호", required = true) @RequestParam String password) {
        User user = userJpaRepo.findByUid(id).orElseThrow(CEmailSigninFailedException::new);
        if (!passwordEncoder.matches(password, user.getPassword()))
            throw new CEmailSigninFailedException();

        return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));

 }

 @ApiOperation(value = "가입", notes = "회원가입을 한다.")
 @PostMapping(value = "/signup")
 public CommonResult signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
                               @ApiParam(value = "비밀번호", required = true) @RequestParam String password,
                               @ApiParam(value = "이름", required = true) @RequestParam String name) {

        userJpaRepo.save(User.builder()
                .uid(id)
                .password(passwordEncoder.encode(password))
                .name(name)
                .roles(Collections.singletonList("ROLE_USER"))
                .build());
        return responseService.getSuccessResult();
    }
}</pre>



<h3 class="wp-block-heading">SpringRestApiApplication에 passwordEncoder bean 추가 </h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@SpringBootApplication
public class SpringRestApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringRestApiApplication.class, args);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}</pre>



<h3 class="wp-block-heading">UserController 수정</h3>



<p class="wp-block-paragraph">유효한 Jwt토큰을 설정해야만 User 리소스를 사용할 수 있도록 Header에 X-AUTH-TOKEN을 인자로 받도록 선언합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Api(tags = {"2. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class UserController {

    private final UserJpaRepo userJpaRepo;
    private final ResponseService responseService; // 결과를 처리할 Service

    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
    @GetMapping(value = "/users")
    public ListResult&lt;User> findAllUser() {
        // 결과데이터가 여러건인경우 getListResult를 이용해서 결과를 출력한다.
        return responseService.getListResult(userJpaRepo.findAll());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
    @GetMapping(value = "/user")
    public SingleResult&lt;User> findUserById(@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
        // SecurityContext에서 인증받은 회원의 정보를 얻어온다.
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = authentication.getName();
        // 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
        return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
    @PutMapping(value = "/user")
    public SingleResult&lt;User> modify(
            @ApiParam(value = "회원번호", required = true) @RequestParam int msrl,
            @ApiParam(value = "회원이름", required = true) @RequestParam String name) {
        User user = User.builder()
                .msrl(msrl)
                .name(name)
                .build();
        return responseService.getSingleResult(userJpaRepo.save(user));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
    @DeleteMapping(value = "/user/{msrl}")
    public CommonResult delete(
            @ApiParam(value = "회원번호", required = true) @PathVariable int msrl) {
        userJpaRepo.deleteById(msrl);
        // 성공 결과 정보만 필요한경우 getSuccessResult()를 이용하여 결과를 출력한다.
        return responseService.getSuccessResult();
    }
}</pre>



<h3 class="wp-block-heading">Test Swagger</h3>



<p class="wp-block-paragraph">회원가입 -&gt; 로그인 -&gt; 토큰을 이용한 회원정보 조회순으로 Test를 진행합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup.png" alt="" class="wp-image-757" width="713" height="746" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup.png 951w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup-768x803.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup-150x157.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup-300x314.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup-696x727.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signup-402x420.png 402w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin.png" alt="" class="wp-image-758" width="713" height="743" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin.png 951w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin-768x799.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin-150x156.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin-300x312.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin-696x725.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/signin-403x420.png 403w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search.png" alt="" class="wp-image-759" width="716" height="972" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search.png 954w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-754x1024.png 754w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-768x1043.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-150x204.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-300x408.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-696x946.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/token_search-309x420.png 309w" sizes="auto, (max-width: 716px) 100vw, 716px" /></figure>



<p class="wp-block-paragraph">인증 토큰을 발급받아 제한된 리소스에 접근하는 것에 대한 테스트가 완료되었습니다.</p>



<h3 class="wp-block-heading">예외 처리 보완</h3>



<p class="wp-block-paragraph">다음과 같은 상황을 예측해 볼 수 있습니다.</p>



<ol class="wp-block-list"><li>Jwt토큰 없이 api를 호출하였을 경우</li><li>형식에 맞지 않거나 만료된 Jwt토큰으로 api를 호출한 경우</li><li>Jwt토큰으로 api를 호출하였으나 해당 리소스에 대한 권한이 없는 경우 </li></ol>



<p class="wp-block-paragraph">1,2 번은 다음과 같은 오류가 발생합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied.png" alt="" class="wp-image-764" width="707" height="168" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied.png 943w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied-768x182.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied-150x36.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied-300x71.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdenied-696x165.png 696w" sizes="auto, (max-width: 707px) 100vw, 707px" /></figure>



<p class="wp-block-paragraph">3번은 다음과 같은 오류가 발생합니다.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden.png" alt="" class="wp-image-765" width="704" height="169" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden.png 939w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden-768x184.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden-150x36.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden-300x72.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/forbidden-696x167.png 696w" sizes="auto, (max-width: 704px) 100vw, 704px" /></figure>



<h3 class="wp-block-heading">커스텀 예외 처리가 적용이 안되는 이유</h3>



<p class="wp-block-paragraph">위의 상황에서 커스텀으로 적용한 예외 처리가 적용이 안 되는 이유는 <strong><span class="has-inline-color has-vivid-red-color">필터링의 순서</span></strong> 때문입니다. 지금까지 적용한 커스텀 예외처리는 ControllerAdvice 즉 Spring이 처리 가능한 영역까지 리퀘스트가 도달해야 처리할 수 있습니다. 그러나 SpringSecurity는 Spring 앞단에서 필터링을 하기 때문에, 해당 상황의 exeption이 Spring의 DispatcherServlet까지 도달하지 않게 됩니다. </p>



<h3 class="wp-block-heading">1,2 번에 대한 해결책 </h3>



<p class="wp-block-paragraph">온전한 Jwt가 전달이 안될 경우는 토큰 인증 처리 자체가 불가능하기 때문에, 토큰 검증 단에서 프로세스가 끝나버리게 됩니다. 해당 예외를 잡아내려면 SpringSecurity에서 제공하는 AuthenticationEntryPoint를 상속받아 재정의 해야 합니다. 예외가 발생할 경우 아래에서는 /exception/entrypoint로 포워딩되도록 처리하였습니다.</p>



<h3 class="wp-block-heading">CustomAuthenticationEntryPoint 작성</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.config.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
            ServletException {
        response.sendRedirect("/exception/entrypoint");
    }
}</pre>



<h3 class="wp-block-heading">ExceptionController 작성</h3>



<p class="wp-block-paragraph">controller package하위에 exception package를 생성하고 ExceptionController를 작성합니다. 내용은 /exception/entrypoint로 주소가 들어오면 CAuthenticationEntryPointException을 발생시키라는 것입니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.controller.exception;

// import 생략

@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/exception")
public class ExceptionController {

    @GetMapping(value = "/entrypoint")
    public CommonResult entrypointException() {
        throw new CAuthenticationEntryPointException();
    }
}</pre>



<h3 class="wp-block-heading">CAuthenticationEntryPointException 생성</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.advice.exception;

public class CAuthenticationEntryPointException extends RuntimeException {
    public CAuthenticationEntryPointException(String msg, Throwable t) {
        super(msg, t);
    }

    public CAuthenticationEntryPointException(String msg) {
        super(msg);
    }

    public CAuthenticationEntryPointException() {
        super();
    }
}</pre>



<h3 class="wp-block-heading">Message 내용 추가</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// exception_ko.yml
entryPointException:
   code: "-1002"
   msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
// exception_en.yml
entryPointException:
   code: "-1002"
   msg: "You do not have permission to access this resource.</pre>



<h3 class="wp-block-heading">ExceptionAdvice 내용 추가</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@ExceptionHandler(CAuthenticationEntryPointException.class)
public CommonResult authenticationEntryPointException(HttpServletRequest request, CAuthenticationEntryPointException e) {
        return responseService.getFailResult(Integer.valueOf(getMessage("entryPointException.code")), getMessage("entryPointException.msg"));
}</pre>



<h3 class="wp-block-heading">SpringSecurityConfiguration에 CustomAuthenticationEntryPoint 설정 추가</h3>



<p class="wp-block-paragraph">.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())를 추가하고 /exception주소를 PermitAll()에 추가한다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Override
protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "/exception/**", "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
                .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
}</pre>



<h3 class="wp-block-heading">Swagger Test</h3>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint.png" alt="" class="wp-image-768" width="708" height="794" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint.png 944w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-913x1024.png 913w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-768x862.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-150x168.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-300x337.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-696x781.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/entrypoint-374x420.png 374w" sizes="auto, (max-width: 708px) 100vw, 708px" /></figure>



<h3 class="wp-block-heading">3번에 대한 해결책</h3>



<p class="wp-block-paragraph">3번은 Jwt토큰은 정상이라는 가정하에 Jwt토큰이 가지지 못한 권한의 리소스를 접근할 때 발생하는 오류입니다. 이 경우에는 SpringSecurity에서 제공하는 AccessDeniedHandler를 상속받아 커스터 마이징 해야 합니다. 예외가 발생할 경우 handler에서는 /exception/accessdenied로 포워딩되도록 하였습니다.</p>



<h3 class="wp-block-heading">CustomAccessDeniedHandler 생성</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.rest.api.config.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
            ServletException {
		response.sendRedirect("/exception/accessdenied");
	}
}</pre>



<h3 class="wp-block-heading">ExceptionController 수정</h3>



<p class="wp-block-paragraph">위에서 생성한 ExceptionController에 다음 내용을 추가합니다. 이미 존재하는 Exception이므로 커스텀 Exception은 따로 만들지 않고 기존 AccessDeniedException을 발생시킵니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@GetMapping(value = "/accessdenied")
public CommonResult accessdeniedException() {
        throw new AccessDeniedException("");
}</pre>



<h3 class="wp-block-heading">Message 내용 추가</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// exception_ko.yml
accessDenied:
  code: "-1003"
  msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
  
// exception_en.yml
accessDenied:
  code: "-1003"
  msg: "A resource that can not be accessed with the privileges it has."</pre>



<h3 class="wp-block-heading" id="mce_103">ExceptionAdvice 내용 추가</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@ExceptionHandler(AccessDeniedException.class)
public CommonResult AccessDeniedException(HttpServletRequest request, AccessDeniedException e) {
        return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
}</pre>



<h3 class="wp-block-heading" id="mce_108">SpringSecurityConfiguration에 CustomAccessDeniedHandler 설정 추가</h3>



<p class="wp-block-paragraph">테스트를 위해 /users api는 ROLE_ADMIN 권한만 접근 가능하게 처리해 놓습니다.<br>.antMatchers(&#8220;/*/users&#8221;).hasRole(&#8220;ADMIN&#8221;)</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Override
protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "/exception/**", "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
                .antMatchers("/*/users").hasRole("ADMIN")
                .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
            .and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
}</pre>



<h3 class="wp-block-heading" id="mce_116">Swagger Test</h3>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok.png" alt="" class="wp-image-775" width="713" height="766" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok.png 951w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok-768x825.png 768w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok-150x161.png 150w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok-300x322.png 300w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok-696x747.png 696w, https://www.daddyprogrammer.org/wp-content/uploads/2019/04/accessdeniedok-391x420.png 391w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>



<p class="wp-block-paragraph">예외 처리 고도화까지 잘 적용되었음을 확인하였습니다. 이제 서버는 어느 정도의 보안성을 갖추게 되었습니다. SpringSecurity를 적용하지 않고 동일한 프로세스를 처음부터 만들려고 했으면, 많은 고난과 예외상황에 대한 대처를 위해 수많은 시간과 노력이 필요했을 것입니다. 그렇지만 SpringSecurity를 적용하는데도 상당한 지식과 노력이 필요합니다. 본문에 나온 내용은 Security의 일부 내용일 뿐입니다. 그만큼 SpringSecurity 내용은 방대합니다. 이 글을 통해 서버를 보다 더 견고하게 만드는 첫걸음이 되었으면 좋겠습니다. </p>



<h3 class="wp-block-heading">추가) annotation으로 리소스 접근 권한 설정</h3>



<p class="wp-block-paragraph">실습에서는 리소스에 대한 접근권한 설정시 아래와 같이 SecurityConfiguration.java의 configure(HttpSecurity http) 메서드 내부에서 authorizeRequests()를 통해 세팅하였습니다. 이렇게 하면 리소스의 권한을 중앙관리한다는 점에서 이점이 있는데요. 추가로 Spring에서는 annotation으로도 권한 설정이 가능하도록 지원하고 있습니다. 각각의 방식은 장단점이 있으므로 상황에 따라 적합한 방법을 채택해 사용하면 될 것 같습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 생략...
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록된 GET요청 리소스는 누구나 접근가능
                    .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            // 생략...
    }</pre>



<h4 class="wp-block-heading">@PreAuthorize, @Secured</h4>



<p class="wp-block-paragraph">권한 설정이 필요한 리소스(실습에서는 Controller의 각 메서드에 해당)에 @PreAuthorize, @Secured로 권한을 세팅할 수 있습니다. 둘다 같은 역할을 하지만 아래와 같은 차이가 있습니다. </p>



<p class="wp-block-paragraph"><strong><span class="has-inline-color has-vivid-cyan-blue-color">@PreAuthorize</span></strong><br>표현식 사용 가능 <br>ex) @PreAuthorize(&#8220;hasRole(&#8216;ROLE_USER&#8217;) and hasRole(&#8216;ROLE_ADMIN&#8217;)&#8221;)<br><strong><span class="has-inline-color has-vivid-cyan-blue-color">@Secured</span></strong><br>표현식 사용 불가능<br>ex) @Secured({&#8220;ROLE_USER&#8221;,&#8221;ROLE_ADMIN&#8221;})</p>



<p class="wp-block-paragraph">annotation으로 권한설정을 하려면 GlobalMethodSecurity를 활성화해야 합니다. 아래와 같이 SecurityConfiguration 상단에 <span class="has-inline-color has-vivid-red-color"><strong>@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)를 추가</strong></span>합니다. 그리고 configure 메서드 안에서<span class="has-inline-color has-vivid-red-color"><strong> authorizeRequest() 설정은 주석 처리하거나 삭제</strong></span>합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
생략...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
//            .and()
//                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
//                    .antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
//                    .antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록된 GET요청 리소스는 누구나 접근가능
//                    .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
            .and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.

    }
생략 ...
}</pre>



<p class="wp-block-paragraph">Controller에 권한을 설정합니다. 만약 Controller 내부의 모든 리소스에 대하여 일괄로 동일한 권한을 설정할 것이면 Controller 상단에 annotation을 세팅합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@PreAuthorize("hasRole('ROLE_USER')") 또는 @Secured("ROLE_USER")
@Api(tags = {"2. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class UserController {
내용 생략....
}</pre>



<p class="wp-block-paragraph">만약 각각의 리소스마다 권한을 설정해야 하면 해당 메서드 위에 annotation을 세팅하면 됩니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Api(tags = {"2. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class UserController {

    private final UserJpaRepo userJpaRepo;
    private final ResponseService responseService; // 결과를 처리할 Service

    @Secured("ROLE_USER")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
    @GetMapping(value = "/users")
    public ListResult&lt;User> findAllUser() {
        // 결과데이터가 여러건인경우 getListResult를 이용해서 결과를 출력한다.
        return responseService.getListResult(userJpaRepo.findAll());
    }

    @PreAuthorize("hasRole('ROLE_USER')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
    @GetMapping(value = "/user")
    public SingleResult&lt;User> findUser() {
        // SecurityContext에서 인증받은 회원의 정보를 얻어온다.
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = authentication.getName();
        // 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
        return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
    }
  생략...
}</pre>



<p class="wp-block-paragraph">위에서 annotation으로 권한을 설정한 리소스 외 나머지 리소스들은 누구나 접근 가능한 리소스로 설정됩니다. </p>



<p class="wp-block-paragraph">최신 소스는 GitHub 사이트를 참고해 주세요.<br><a href="https://github.com/codej99/SpringRestApi/tree/feature/security">https://github.com/codej99/SpringRestApi/tree/feature/security</a></p>



<p class="wp-block-paragraph">GitHub Repository를 import하여 Intellij 프로젝트를 구성하는 방법은 다음 포스팅을 참고해주세요.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="ZqWxMQMypJ"><a href="https://www.daddyprogrammer.org/post/1215/intellij-github-spring-gradle-project-import/">Intellij에서 Github의 Spring Gradle Project import 하기</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Intellij에서 Github의 Spring Gradle Project import 하기&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/1215/intellij-github-spring-gradle-project-import/embed/#?secret=KRVVWkcPQa#?secret=ZqWxMQMypJ" data-secret="ZqWxMQMypJ" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p class="wp-block-paragraph">Docker로 개발 환경을 빠르게 구축하는 것도 가능합니다. 다음 블로그 내용을 읽어보세요!</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="oZJ3sWluFw"><a href="https://www.daddyprogrammer.org/post/1994/docker-kitematic-mysql-redis-rabbitmq-mongo/">Docker로 빠르게 개발환경 구성하기(mysql, redis, rabbitmq, mongoDB)</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Docker로 빠르게 개발환경 구성하기(mysql, redis, rabbitmq, mongoDB)&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/1994/docker-kitematic-mysql-redis-rabbitmq-mongo/embed/#?secret=heugkw4ea2#?secret=oZJ3sWluFw" data-secret="oZJ3sWluFw" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p class="wp-block-paragraph">스프링 api 서버를 이용하여 웹사이트를 만들어보고 싶으시면 아래 포스팅을 참고해 주세요.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-아빠프로그래머의-좌충우돌-개발하기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="OFEUbj3B9u"><a href="https://www.daddyprogrammer.org/post/6237/rest-api-angular-framework-make-website/">Spring Rest api + Angular framework로 웹사이트 만들기(1) &#8211; 프로젝트 구성 및 반응형 레이아웃 구현</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Spring Rest api + Angular framework로 웹사이트 만들기(1) &#8211; 프로젝트 구성 및 반응형 레이아웃 구현&#8221; &#8212; 아빠프로그래머의 좌충우돌 개발하기!" src="https://www.daddyprogrammer.org/post/6237/rest-api-angular-framework-make-website/embed/#?secret=RpHzsbEwcQ#?secret=OFEUbj3B9u" data-secret="OFEUbj3B9u" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p class="wp-block-paragraph"></p>
<p>The post <a href="https://www.daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/">SpringBoot2로 Rest api 만들기(8) –  SpringSecurity 를 이용한 인증 및 권한부여</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/feed/</wfw:commentRss>
			<slash:comments>93</slash:comments>
		
		
		
		<series:name><![CDATA[SpringBoot2로 Rest api 만들기]]></series:name>
	</item>
	</channel>
</rss>
