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 c71f97c

Browse files
author
dimMaryanto@win10
committed
init project oauth2 authorization and resource server configuration
0 parents commit c71f97c

File tree

9 files changed

+393
-0
lines changed

9 files changed

+393
-0
lines changed

‎.gitignore‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
target/
2+
.mvn/
3+
4+
### STS ###
5+
.apt_generated
6+
.classpath
7+
.factorypath
8+
.project
9+
.settings
10+
.springBeans
11+
.sts4-cache
12+
13+
### IntelliJ IDEA ###
14+
.idea
15+
*.iws
16+
*.iml
17+
*.ipr
18+
19+
### NetBeans ###
20+
nbproject/private/
21+
build/
22+
nbbuild/
23+
dist/
24+
nbdist/
25+
.nb-gradle/
26+
27+
## systemfiles
28+
.DS_Store

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Security Oauth2 with LDAP
2+
3+
## Request token
4+
5+
```bash
6+
curl -X POST \
7+
'http://localhost:8080/oauth/token?grant_type=password&username=user&password=password&client_id=mandiri_mits' \
8+
-H 'Authorization: Basic bWFuZGlyaV9taXRzOjEyMzQ1Ng=='
9+
```

‎pom.xml‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.maryanto.dimas.example</groupId>
7+
<artifactId>springboot-oauth2-ldap-example</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>springboot-oauth2-ldap</name>
12+
<description>Demo project for Spring Boot</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>1.5.14.RELEASE</version>
18+
<relativePath/> <!-- lookup parent from repository -->
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24+
<java.version>1.8</java.version>
25+
</properties>
26+
27+
<dependencies>
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter-data-ldap</artifactId>
31+
</dependency>
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-security</artifactId>
35+
</dependency>
36+
<dependency>
37+
<groupId>org.springframework.security.oauth</groupId>
38+
<artifactId>spring-security-oauth2</artifactId>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.springframework.security</groupId>
42+
<artifactId>spring-security-jwt</artifactId>
43+
</dependency>
44+
<dependency>
45+
<groupId>net.sourceforge.collections</groupId>
46+
<artifactId>collections-generic</artifactId>
47+
<version>4.01</version>
48+
</dependency>
49+
<dependency>
50+
<groupId>org.apache.commons</groupId>
51+
<artifactId>commons-collections4</artifactId>
52+
<version>4.1</version>
53+
</dependency>
54+
<dependency>
55+
<groupId>com.google.guava</groupId>
56+
<artifactId>guava</artifactId>
57+
<version>20.0</version>
58+
</dependency>
59+
60+
<dependency>
61+
<groupId>org.springframework.boot</groupId>
62+
<artifactId>spring-boot-starter-web</artifactId>
63+
</dependency>
64+
<dependency>
65+
<groupId>org.projectlombok</groupId>
66+
<artifactId>lombok</artifactId>
67+
<optional>true</optional>
68+
</dependency>
69+
<dependency>
70+
<groupId>org.springframework.boot</groupId>
71+
<artifactId>spring-boot-starter-test</artifactId>
72+
<scope>test</scope>
73+
</dependency>
74+
<dependency>
75+
<groupId>org.springframework.security</groupId>
76+
<artifactId>spring-security-test</artifactId>
77+
<scope>test</scope>
78+
</dependency>
79+
</dependencies>
80+
81+
<build>
82+
<plugins>
83+
<plugin>
84+
<groupId>org.springframework.boot</groupId>
85+
<artifactId>spring-boot-maven-plugin</artifactId>
86+
</plugin>
87+
</plugins>
88+
</build>
89+
90+
91+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.maryanto.dimas.example;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class OAuth2LdapApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(OAuth2LdapApplication.class, args);
11+
}
12+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.maryanto.dimas.example.configurations;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
7+
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
8+
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
9+
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
10+
import org.springframework.security.oauth2.provider.token.TokenStore;
11+
12+
@EnableResourceServer
13+
@Configuration
14+
public class OauthResourceServerConfiguration extends ResourceServerConfigurerAdapter {
15+
16+
17+
@Autowired
18+
private OAuth2AccessDeniedHandler handler;
19+
20+
@Autowired
21+
private TokenStore tokenStore;
22+
23+
@Value("${oauth2.resource_id}")
24+
private String RESOURCE_ID;
25+
26+
@Override
27+
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
28+
// super.configure(resources);
29+
resources.resourceId(RESOURCE_ID)
30+
.tokenStore(tokenStore)
31+
.accessDeniedHandler(handler)
32+
.stateless(false);
33+
}
34+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.maryanto.dimas.example.configurations;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Qualifier;
5+
import org.springframework.beans.factory.annotation.Value;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.security.authentication.AuthenticationManager;
9+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
10+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
11+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
12+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
13+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
14+
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
15+
import org.springframework.security.oauth2.provider.token.TokenStore;
16+
17+
@Configuration
18+
@EnableAuthorizationServer
19+
public class OauthServerConfiguration extends AuthorizationServerConfigurerAdapter {
20+
21+
@Value("${oauth2.resource_id}")
22+
private String RESOURCE_ID;
23+
@Value("${oauth2.client_id}")
24+
private String CLIENT_ID;
25+
@Value("${oauth2.client_secret}")
26+
private String CLIENT_SECRET;
27+
28+
@Autowired
29+
private TokenStore tokenStore;
30+
31+
@Autowired
32+
@Qualifier("authenticationManagerBean")
33+
private AuthenticationManager authenticationManager;
34+
35+
@Bean
36+
public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
37+
return new OAuth2AccessDeniedHandler();
38+
}
39+
40+
41+
@Override
42+
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
43+
oauthServer.checkTokenAccess("permitAll()");
44+
}
45+
46+
@Override
47+
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
48+
clients.inMemory()
49+
.withClient(CLIENT_ID)
50+
.secret(CLIENT_SECRET)
51+
.scopes("read", "write", "trust")
52+
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
53+
.authorities("CLIENT_APP")
54+
.resourceIds(RESOURCE_ID)
55+
.autoApprove(true);
56+
}
57+
58+
@Override
59+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
60+
endpoints
61+
.tokenStore(tokenStore)
62+
.authenticationManager(authenticationManager);
63+
}
64+
}
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
package com.maryanto.dimas.example.configurations;
2+
3+
import com.google.common.collect.ImmutableList;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.boot.autoconfigure.security.SecurityProperties;
6+
import org.springframework.boot.web.servlet.FilterRegistrationBean;
7+
import org.springframework.context.annotation.Bean;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.core.annotation.Order;
10+
import org.springframework.security.authentication.AuthenticationManager;
11+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
12+
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
13+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
14+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
15+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
16+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
17+
import org.springframework.security.config.http.SessionCreationPolicy;
18+
import org.springframework.security.oauth2.provider.ClientDetailsService;
19+
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
20+
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
21+
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
22+
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
23+
import org.springframework.security.oauth2.provider.token.TokenStore;
24+
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
25+
import org.springframework.web.cors.CorsConfiguration;
26+
import org.springframework.web.cors.CorsConfigurationSource;
27+
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
28+
import org.springframework.web.filter.CorsFilter;
29+
30+
@Configuration
31+
@EnableWebSecurity
32+
@EnableGlobalMethodSecurity(securedEnabled = true)
33+
@EnableGlobalAuthentication
34+
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
35+
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
36+
37+
38+
@Autowired
39+
private ClientDetailsService clientDetailsService;
40+
41+
@Bean
42+
@Override
43+
public AuthenticationManager authenticationManagerBean() throws Exception {
44+
return super.authenticationManagerBean();
45+
}
46+
47+
@Override
48+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
49+
// super.configure(auth);
50+
auth.inMemoryAuthentication()
51+
.withUser("user").password("password").roles("USER").and()
52+
.withUser("admin").password("password").roles("ADMIN", "USER");
53+
}
54+
55+
@Override
56+
protected void configure(HttpSecurity http) throws Exception {
57+
// super.configure(http);
58+
http
59+
.csrf().disable()
60+
.cors().disable()
61+
.authorizeRequests()
62+
.antMatchers("/oauth/**").permitAll()
63+
.anyRequest().authenticated()
64+
.and().httpBasic()
65+
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
66+
}
67+
68+
69+
@Bean
70+
@Autowired
71+
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
72+
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
73+
handler.setTokenStore(tokenStore);
74+
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
75+
handler.setClientDetailsService(clientDetailsService);
76+
return handler;
77+
}
78+
79+
@Bean
80+
@Autowired
81+
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
82+
TokenApprovalStore store = new TokenApprovalStore();
83+
store.setTokenStore(tokenStore);
84+
return store;
85+
}
86+
87+
@Bean
88+
public FilterRegistrationBean corsFilter() {
89+
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
90+
CorsConfiguration config = new CorsConfiguration();
91+
config.setAllowCredentials(true);
92+
config.addAllowedOrigin("*");
93+
config.addAllowedHeader("*");
94+
config.addAllowedMethod("*");
95+
config.setAllowCredentials(true);
96+
source.registerCorsConfiguration("/**", config);
97+
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
98+
bean.setOrder(0);
99+
return bean;
100+
}
101+
102+
103+
@Bean
104+
public CorsConfigurationSource corsConfigurationSource() {
105+
final CorsConfiguration configuration = new CorsConfiguration();
106+
configuration.setAllowedMethods(ImmutableList.of("HEAD",
107+
"GET", "POST", "PUT", "DELETE", "PATCH"));
108+
configuration.setAllowedOrigins(ImmutableList.of("*"));
109+
configuration.setAllowCredentials(true);
110+
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
111+
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
112+
source.registerCorsConfiguration("/**", configuration);
113+
return source;
114+
}
115+
116+
117+
@Bean
118+
public TokenStore tokenStore() {
119+
return new InMemoryTokenStore();
120+
}
121+
122+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.maryanto.dimas.example.controllers;
2+
3+
import org.apache.commons.collections4.map.HashedMap;
4+
import org.springframework.http.ResponseEntity;
5+
import org.springframework.security.access.prepost.PreAuthorize;
6+
import org.springframework.security.core.Authentication;
7+
import org.springframework.web.bind.annotation.PostMapping;
8+
import org.springframework.web.bind.annotation.RequestMapping;
9+
import org.springframework.web.bind.annotation.RestController;
10+
11+
import java.util.Date;
12+
import java.util.Map;
13+
14+
import static org.springframework.http.ResponseEntity.ok;
15+
16+
@RestController
17+
@RequestMapping("/api/users")
18+
public class UserApi {
19+
20+
@PostMapping("/me")
21+
@PreAuthorize("hasRole('USER')")
22+
public ResponseEntity<?> getUserLogin(Authentication principal) {
23+
Map<String, Object> params = new HashedMap<>();
24+
params.put("time", new Date());
25+
params.put("currentUser", principal.getName());
26+
return ok().body(params);
27+
}
28+
}

0 commit comments

Comments
(0)

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