Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 611a4f6

Browse files
author
kimyonghwa
committed
Build spring boot - oauth2 authorization server
1 parent cd3d4be commit 611a4f6

File tree

10 files changed

+290
-0
lines changed

10 files changed

+290
-0
lines changed

‎README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,20 @@
11
# SpringOauth2AuthorizationServer
22
Spring Oauth2 AuthorizationServer
3+
4+
5+
6+
## Oauth2 Authorize
7+
http://localhost:8081/oauth/authorize?client_id=testClientId&redirect_uri=http://localhost:8081/oauth2/callback&response_type=code&scope=read
8+
9+
## publish token
10+
curl -X POST \
11+
'http://localhost:8080/oauth/token' \
12+
-H 'Authorization:Basic dGVzdENsaWVudElkOnRlc3RTZWNyZXQ=' \
13+
-d 'grant_type=authorization_code' \
14+
-d 'code=9THJxB' \
15+
-d 'redirect_uri=http://localhost:8080/oauth2/callback'
16+
17+
## add client
18+
19+
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)
20+
values('testClientId',null,'testSecret','read','authorization_code','http://localhost:8081/oauth2/callback','ROLE_USER',36000,50000,null,null);

‎build.gradle‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ dependencies {
2323
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
2424
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
2525
implementation 'org.springframework.boot:spring-boot-starter-web'
26+
implementation 'org.springframework.boot:spring-boot-starter-security'
27+
implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.4.RELEASE'
28+
implementation 'com.google.code.gson:gson'
2629
compileOnly 'org.projectlombok:lombok'
2730
runtimeOnly 'com.h2database:h2'
2831
runtimeOnly 'mysql:mysql-connector-java'

‎src/main/java/com/rest/oauth2/Oauth2Application.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.web.client.RestTemplate;
57

68
@SpringBootApplication
79
public class Oauth2Application {
@@ -10,4 +12,8 @@ public static void main(String[] args) {
1012
SpringApplication.run(Oauth2Application.class, args);
1113
}
1214

15+
@Bean
16+
public RestTemplate getRestTemplate() {
17+
return new RestTemplate();
18+
}
1319
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.rest.oauth2.config;
2+
3+
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.Configuration;
7+
import org.springframework.context.annotation.Primary;
8+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
9+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
10+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
11+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
12+
import org.springframework.security.oauth2.provider.ClientDetailsService;
13+
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
14+
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
15+
16+
import javax.sql.DataSource;
17+
18+
@Configuration
19+
@EnableAuthorizationServer
20+
public class Oauth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
21+
22+
23+
@Autowired
24+
private ClientDetailsService clientDetailsService;
25+
26+
@Override
27+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
28+
super.configure(endpoints);
29+
endpoints.accessTokenConverter(jwtAccessTokenConverter());
30+
}
31+
32+
@Override
33+
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
34+
clients.withClientDetails(clientDetailsService);
35+
}
36+
37+
@Bean
38+
@Primary
39+
public JdbcClientDetailsService jdbcClientDetailsService(DataSource dataSource) {
40+
return new JdbcClientDetailsService(dataSource);
41+
}
42+
43+
@Bean
44+
public JwtAccessTokenConverter jwtAccessTokenConverter() {
45+
return new JwtAccessTokenConverter();
46+
}
47+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.rest.oauth2.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
10+
import org.springframework.security.crypto.password.PasswordEncoder;
11+
12+
@Configuration
13+
@EnableWebSecurity
14+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
15+
16+
@Bean
17+
public PasswordEncoder noOpPasswordEncoder() {
18+
return NoOpPasswordEncoder.getInstance();
19+
}
20+
21+
@Override
22+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
23+
auth.inMemoryAuthentication()
24+
.withUser("user")
25+
.password("pass")
26+
.roles("USER")
27+
.and()
28+
.withUser("admin")
29+
.password("pass")
30+
.roles("USER", "ADMIN");
31+
}
32+
33+
@Override
34+
protected void configure(HttpSecurity security) throws Exception {
35+
security
36+
.csrf().disable()
37+
.headers().frameOptions().disable()
38+
.and()
39+
.authorizeRequests().antMatchers("/oauth/**", "/oauth2/callback", "/h2-console/*").permitAll()
40+
.and()
41+
.formLogin().and()
42+
.httpBasic();
43+
}
44+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.rest.oauth2.controller.common;
2+
3+
import com.google.gson.Gson;
4+
import com.rest.oauth2.model.oauth2.OAuthToken;
5+
import lombok.RequiredArgsConstructor;
6+
import org.apache.commons.codec.binary.Base64;
7+
import org.springframework.beans.factory.annotation.Value;
8+
import org.springframework.http.*;
9+
import org.springframework.util.LinkedMultiValueMap;
10+
import org.springframework.util.MultiValueMap;
11+
import org.springframework.web.bind.annotation.GetMapping;
12+
import org.springframework.web.bind.annotation.RequestMapping;
13+
import org.springframework.web.bind.annotation.RequestParam;
14+
import org.springframework.web.bind.annotation.RestController;
15+
import org.springframework.web.client.RestTemplate;
16+
17+
@RequiredArgsConstructor
18+
@RestController
19+
@RequestMapping("/oauth2")
20+
public class Oauth2Controller {
21+
22+
@Value("${oauth2.clientId}")
23+
private String clientId;
24+
25+
@Value("${oauth2.secret}")
26+
private String secret;
27+
28+
@Value("${oauth2.callback}")
29+
private String callback;
30+
31+
@Value("${oauth2.grantType}")
32+
private String grantType;
33+
34+
@Value("${oauth2.token}")
35+
private String tokenUrl;
36+
37+
38+
private final Gson gson;
39+
40+
private final RestTemplate restTemplate;
41+
42+
@GetMapping(value = "/callback")
43+
public OAuthToken callbackSocial(@RequestParam String code) {
44+
45+
String credentials = clientId + ":" + secret;
46+
String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));
47+
48+
HttpHeaders headers = new HttpHeaders();
49+
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
50+
headers.add("Authorization", "Basic " + encodedCredentials);
51+
52+
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
53+
params.add("code", code);
54+
params.add("grant_type", grantType);
55+
params.add("redirect_uri", callback);
56+
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
57+
ResponseEntity<String> response = restTemplate.postForEntity(tokenUrl, request, String.class);
58+
if (response.getStatusCode() == HttpStatus.OK) {
59+
return gson.fromJson(response.getBody(), OAuthToken.class);
60+
}
61+
return null;
62+
}
63+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.rest.oauth2.model.oauth2;
2+
3+
import lombok.Getter;
4+
import lombok.Setter;
5+
6+
@Getter
7+
@Setter
8+
public class OAuthToken {
9+
private String access_token;
10+
private String token_type;
11+
private String refresh_token;
12+
private long expires_in;
13+
private String scope;
14+
}

‎src/main/resources/application.yml‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
1+
server:
2+
port: 8081
13

4+
oauth2:
5+
callback: http://localhost:8081/oauth2/callback
6+
token: http://localhost:8081/oauth/token
7+
8+
spring:
9+
h2:
10+
console:
11+
enabled: true
12+
settings:
13+
web-allow-others: true
14+
datasource:
15+
url: jdbc:h2:tcp://localhost/~/test
16+
driver-class-name: org.h2.Driver
17+
username: sa
18+
jpa:
19+
database-platform: org.hibernate.dialect.H2Dialect
20+
properties.hibernate.hbm2ddl.auto: none
21+
showSql: true

‎src/main/resources/schema.sql‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
-- used in tests that use HSQL
2+
create table IF NOT EXISTS oauth_client_details (
3+
client_id VARCHAR(256) PRIMARY KEY,
4+
resource_ids VARCHAR(256),
5+
client_secret VARCHAR(256),
6+
scope VARCHAR(256),
7+
authorized_grant_types VARCHAR(256),
8+
web_server_redirect_uri VARCHAR(256),
9+
authorities VARCHAR(256),
10+
access_token_validity INTEGER,
11+
refresh_token_validity INTEGER,
12+
additional_information VARCHAR(4096),
13+
autoapprove VARCHAR(256)
14+
);
15+
16+
create table IF NOT EXISTS oauth_client_token (
17+
token_id VARCHAR(256),
18+
token LONGVARBINARY,
19+
authentication_id VARCHAR(256) PRIMARY KEY,
20+
user_name VARCHAR(256),
21+
client_id VARCHAR(256)
22+
);
23+
24+
create table IF NOT EXISTS oauth_access_token (
25+
token_id VARCHAR(256),
26+
token LONGVARBINARY,
27+
authentication_id VARCHAR(256) PRIMARY KEY,
28+
user_name VARCHAR(256),
29+
client_id VARCHAR(256),
30+
authentication LONGVARBINARY,
31+
refresh_token VARCHAR(256)
32+
);
33+
34+
create table IF NOT EXISTS oauth_refresh_token (
35+
token_id VARCHAR(256),
36+
token LONGVARBINARY,
37+
authentication LONGVARBINARY
38+
);
39+
40+
create table IF NOT EXISTS oauth_code (
41+
code VARCHAR(256), authentication LONGVARBINARY
42+
);
43+
44+
create table IF NOT EXISTS oauth_approvals (
45+
userId VARCHAR(256),
46+
clientId VARCHAR(256),
47+
scope VARCHAR(256),
48+
status VARCHAR(10),
49+
expiresAt TIMESTAMP,
50+
lastModifiedAt TIMESTAMP
51+
);
52+
53+
54+
-- customized oauth_client_details table
55+
create table IF NOT EXISTS ClientDetails (
56+
appId VARCHAR(256) PRIMARY KEY,
57+
resourceIds VARCHAR(256),
58+
appSecret VARCHAR(256),
59+
scope VARCHAR(256),
60+
grantTypes VARCHAR(256),
61+
redirectUrl VARCHAR(256),
62+
authorities VARCHAR(256),
63+
access_token_validity INTEGER,
64+
refresh_token_validity INTEGER,
65+
additionalInformation VARCHAR(4096),
66+
autoApproveScopes VARCHAR(256)
67+
);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
package com.rest.oauth2;
22

3+
import lombok.extern.slf4j.Slf4j;
34
import org.junit.Test;
45
import org.junit.runner.RunWith;
6+
import org.springframework.beans.factory.annotation.Autowired;
57
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.security.crypto.password.PasswordEncoder;
69
import org.springframework.test.context.junit4.SpringRunner;
710

11+
@Slf4j
812
@RunWith(SpringRunner.class)
913
@SpringBootTest
1014
public class Oauth2ApplicationTests {
1115

16+
@Autowired
17+
private PasswordEncoder passwordEncoder;
18+
1219
@Test
1320
public void contextLoads() {
21+
log.info(passwordEncoder.encode("password"));
1422
}
1523

1624
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /