Skip to content

Commit 4535831

Browse files
committed
OpenID Connect example
1 parent b0d8d83 commit 4535831

10 files changed

Lines changed: 441 additions & 0 deletions

File tree

‎spring-openid/.classpath‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" output="target/classes" path="src/main/java">
4+
<attributes>
5+
<attribute name="optional" value="true"/>
6+
<attribute name="maven.pomderived" value="true"/>
7+
</attributes>
8+
</classpathentry>
9+
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
10+
<attributes>
11+
<attribute name="maven.pomderived" value="true"/>
12+
</attributes>
13+
</classpathentry>
14+
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
15+
<attributes>
16+
<attribute name="optional" value="true"/>
17+
<attribute name="maven.pomderived" value="true"/>
18+
</attributes>
19+
</classpathentry>
20+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
21+
<attributes>
22+
<attribute name="maven.pomderived" value="true"/>
23+
</attributes>
24+
</classpathentry>
25+
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
26+
<attributes>
27+
<attribute name="maven.pomderived" value="true"/>
28+
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
29+
</attributes>
30+
</classpathentry>
31+
<classpathentry kind="output" path="target/classes"/>
32+
</classpath>

‎spring-openid/.project‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<projectDescription>
3+
<name>spring-openid</name>
4+
<comment></comment>
5+
<projects>
6+
</projects>
7+
<buildSpec>
8+
<buildCommand>
9+
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
10+
<arguments>
11+
</arguments>
12+
</buildCommand>
13+
<buildCommand>
14+
<name>org.eclipse.jdt.core.javabuilder</name>
15+
<arguments>
16+
</arguments>
17+
</buildCommand>
18+
<buildCommand>
19+
<name>org.eclipse.wst.common.project.facet.core.builder</name>
20+
<arguments>
21+
</arguments>
22+
</buildCommand>
23+
<buildCommand>
24+
<name>org.springframework.ide.eclipse.core.springbuilder</name>
25+
<arguments>
26+
</arguments>
27+
</buildCommand>
28+
<buildCommand>
29+
<name>org.eclipse.wst.validation.validationbuilder</name>
30+
<arguments>
31+
</arguments>
32+
</buildCommand>
33+
<buildCommand>
34+
<name>org.eclipse.m2e.core.maven2Builder</name>
35+
<arguments>
36+
</arguments>
37+
</buildCommand>
38+
</buildSpec>
39+
<natures>
40+
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
41+
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
42+
<nature>org.springframework.ide.eclipse.core.springnature</nature>
43+
<nature>org.eclipse.jdt.core.javanature</nature>
44+
<nature>org.eclipse.m2e.core.maven2Nature</nature>
45+
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
46+
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
47+
</natures>
48+
</projectDescription>

‎spring-openid/pom.xml‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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>org.baeldung</groupId>
7+
<artifactId>spring-openid</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>war</packaging>
10+
11+
<name>spring-openid</name>
12+
<description>Spring OpenID sample project</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>1.3.2.RELEASE</version>
18+
</parent>
19+
20+
21+
22+
<dependencies>
23+
<dependency>
24+
<groupId>org.springframework.boot</groupId>
25+
<artifactId>spring-boot-starter-security</artifactId>
26+
</dependency>
27+
<dependency>
28+
<groupId>org.springframework.boot</groupId>
29+
<artifactId>spring-boot-starter-web</artifactId>
30+
</dependency>
31+
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-tomcat</artifactId>
35+
<scope>provided</scope>
36+
</dependency>
37+
38+
<dependency>
39+
<groupId>org.springframework.security.oauth</groupId>
40+
<artifactId>spring-security-oauth2</artifactId>
41+
</dependency>
42+
43+
<dependency>
44+
<groupId>org.springframework.security</groupId>
45+
<artifactId>spring-security-jwt</artifactId>
46+
</dependency>
47+
48+
<dependency>
49+
<groupId>org.springframework.boot</groupId>
50+
<artifactId>spring-boot-starter-test</artifactId>
51+
<scope>test</scope>
52+
</dependency>
53+
</dependencies>
54+
55+
<build>
56+
<plugins>
57+
<plugin>
58+
<groupId>org.springframework.boot</groupId>
59+
<artifactId>spring-boot-maven-plugin</artifactId>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
<properties>
65+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
66+
<java.version>1.8</java.version>
67+
</properties>
68+
</project>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package org.baeldung.config;
2+
3+
import java.util.Arrays;
4+
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.oauth2.client.OAuth2ClientContext;
9+
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
10+
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
11+
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
12+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
13+
14+
@Configuration
15+
@EnableOAuth2Client
16+
public class GoogleOpenIdConnectConfig {
17+
@Value("${google.clientId}")
18+
private String clientId;
19+
20+
@Value("${google.clientSecret}")
21+
private String clientSecret;
22+
23+
@Value("${google.accessTokenUri}")
24+
private String accessTokenUri;
25+
26+
@Value("${google.userAuthorizationUri}")
27+
private String userAuthorizationUri;
28+
29+
@Value("${google.redirectUri}")
30+
private String redirectUri;
31+
32+
@Bean
33+
public OAuth2ProtectedResourceDetails googleOpenId() {
34+
final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
35+
details.setClientId(clientId);
36+
details.setClientSecret(clientSecret);
37+
details.setAccessTokenUri(accessTokenUri);
38+
details.setUserAuthorizationUri(userAuthorizationUri);
39+
details.setScope(Arrays.asList("openid", "email"));
40+
details.setPreEstablishedRedirectUri(redirectUri);
41+
details.setUseCurrentUri(false);
42+
return details;
43+
}
44+
45+
@Bean
46+
public OAuth2RestTemplate googleOpenIdTemplate(final OAuth2ClientContext clientContext) {
47+
final OAuth2RestTemplate template = new OAuth2RestTemplate(googleOpenId(), clientContext);
48+
return template;
49+
}
50+
51+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.config;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.security.core.context.SecurityContextHolder;
6+
import org.springframework.stereotype.Controller;
7+
import org.springframework.web.bind.annotation.RequestMapping;
8+
import org.springframework.web.bind.annotation.ResponseBody;
9+
10+
@Controller
11+
public class HomeController {
12+
private final Logger logger = LoggerFactory.getLogger(getClass());
13+
14+
@RequestMapping("/")
15+
@ResponseBody
16+
public final String home() {
17+
final String username = SecurityContextHolder.getContext().getAuthentication().getName();
18+
logger.info(username);
19+
return "Welcome, " + username;
20+
}
21+
22+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package org.baeldung.config;
2+
3+
import org.baeldung.security.OpenIdConnectFilter;
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.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
12+
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
13+
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
14+
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
15+
16+
@Configuration
17+
@EnableWebSecurity
18+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
19+
@Autowired
20+
private OAuth2RestTemplate restTemplate;
21+
22+
@Override
23+
public void configure(WebSecurity web) throws Exception {
24+
web.ignoring().antMatchers("/resources/**");
25+
}
26+
27+
@Bean
28+
public OpenIdConnectFilter myFilter() {
29+
final OpenIdConnectFilter filter = new OpenIdConnectFilter("/google-login");
30+
filter.setRestTemplate(restTemplate);
31+
return filter;
32+
}
33+
34+
@Override
35+
protected void configure(HttpSecurity http) throws Exception {
36+
// @formatter:off
37+
http
38+
.addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class)
39+
.addFilterAfter(myFilter(), OAuth2ClientContextFilter.class)
40+
.httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/google-login"))
41+
.and()
42+
.authorizeRequests()
43+
// .antMatchers("/","/index*").permitAll()
44+
.anyRequest().authenticated()
45+
;
46+
47+
// @formatter:on
48+
}
49+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringOpenidApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringOpenidApplication.class, args);
11+
}
12+
13+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package org.baeldung.security;
2+
3+
import java.io.IOException;
4+
import java.util.Map;
5+
6+
import javax.servlet.ServletException;
7+
import javax.servlet.http.HttpServletRequest;
8+
import javax.servlet.http.HttpServletResponse;
9+
10+
import org.springframework.security.authentication.AuthenticationManager;
11+
import org.springframework.security.authentication.BadCredentialsException;
12+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13+
import org.springframework.security.core.Authentication;
14+
import org.springframework.security.core.AuthenticationException;
15+
import org.springframework.security.jwt.Jwt;
16+
import org.springframework.security.jwt.JwtHelper;
17+
import org.springframework.security.oauth2.client.OAuth2RestOperations;
18+
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
19+
import org.springframework.security.oauth2.common.OAuth2AccessToken;
20+
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
21+
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
22+
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
23+
24+
import com.fasterxml.jackson.databind.ObjectMapper;
25+
26+
public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter {
27+
public OAuth2RestOperations restTemplate;
28+
29+
public OpenIdConnectFilter(String defaultFilterProcessesUrl) {
30+
super(defaultFilterProcessesUrl);
31+
setAuthenticationManager(new NoopAuthenticationManager());
32+
}
33+
34+
@Override
35+
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
36+
37+
OAuth2AccessToken accessToken;
38+
try {
39+
accessToken = restTemplate.getAccessToken();
40+
} catch (final OAuth2Exception e) {
41+
throw new BadCredentialsException("Could not obtain access token", e);
42+
}
43+
try {
44+
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
45+
final Jwt tokenDecoded = JwtHelper.decode(idToken);
46+
System.out.println("===== : " + tokenDecoded.getClaims());
47+
48+
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
49+
50+
final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
51+
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
52+
} catch (final InvalidTokenException e) {
53+
throw new BadCredentialsException("Could not obtain user details from token", e);
54+
}
55+
56+
}
57+
58+
public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
59+
restTemplate = restTemplate2;
60+
61+
}
62+
63+
private static class NoopAuthenticationManager implements AuthenticationManager {
64+
65+
@Override
66+
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
67+
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
68+
}
69+
70+
}
71+
}

0 commit comments

Comments
 (0)