[BAEL-9552] - Create spring-security-modules folder
This commit is contained in:
+51
@@ -0,0 +1,51 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.oauth2.client.OAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
|
||||
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
|
||||
|
||||
@Configuration
|
||||
@EnableOAuth2Client
|
||||
public class GoogleOpenIdConnectConfig {
|
||||
@Value("${google.clientId}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${google.clientSecret}")
|
||||
private String clientSecret;
|
||||
|
||||
@Value("${google.accessTokenUri}")
|
||||
private String accessTokenUri;
|
||||
|
||||
@Value("${google.userAuthorizationUri}")
|
||||
private String userAuthorizationUri;
|
||||
|
||||
@Value("${google.redirectUri}")
|
||||
private String redirectUri;
|
||||
|
||||
@Bean
|
||||
public OAuth2ProtectedResourceDetails googleOpenId() {
|
||||
final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
|
||||
details.setClientId(clientId);
|
||||
details.setClientSecret(clientSecret);
|
||||
details.setAccessTokenUri(accessTokenUri);
|
||||
details.setUserAuthorizationUri(userAuthorizationUri);
|
||||
details.setScope(Arrays.asList("openid", "email"));
|
||||
details.setPreEstablishedRedirectUri(redirectUri);
|
||||
details.setUseCurrentUri(false);
|
||||
return details;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2RestTemplate googleOpenIdTemplate(final OAuth2ClientContext clientContext) {
|
||||
final OAuth2RestTemplate template = new OAuth2RestTemplate(googleOpenId(), clientContext);
|
||||
return template;
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class HomeController {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@RequestMapping("/")
|
||||
@ResponseBody
|
||||
public final String home() {
|
||||
final String username = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
logger.info(username);
|
||||
return "Welcome, " + username;
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.baeldung.security.OpenIdConnectFilter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
private OAuth2RestTemplate restTemplate;
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) throws Exception {
|
||||
web.ignoring().antMatchers("/resources/**");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OpenIdConnectFilter myFilter() {
|
||||
final OpenIdConnectFilter filter = new OpenIdConnectFilter("/google-login");
|
||||
filter.setRestTemplate(restTemplate);
|
||||
return filter;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class)
|
||||
.addFilterAfter(myFilter(), OAuth2ClientContextFilter.class)
|
||||
.httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/google-login"))
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
// .antMatchers("/","/index*").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
;
|
||||
|
||||
// @formatter:on
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package org.baeldung.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringOpenidApplication extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringOpenidApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.jwt.Jwt;
|
||||
import org.springframework.security.jwt.JwtHelper;
|
||||
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestOperations;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
||||
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
|
||||
|
||||
import com.auth0.jwk.Jwk;
|
||||
import com.auth0.jwk.JwkProvider;
|
||||
import com.auth0.jwk.UrlJwkProvider;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter {
|
||||
@Value("${google.clientId}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${google.issuer}")
|
||||
private String issuer;
|
||||
|
||||
@Value("${google.jwkUrl}")
|
||||
private String jwkUrl;
|
||||
|
||||
public OAuth2RestOperations restTemplate;
|
||||
|
||||
public OpenIdConnectFilter(String defaultFilterProcessesUrl) {
|
||||
super(defaultFilterProcessesUrl);
|
||||
setAuthenticationManager(new NoopAuthenticationManager());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
|
||||
|
||||
OAuth2AccessToken accessToken;
|
||||
try {
|
||||
accessToken = restTemplate.getAccessToken();
|
||||
} catch (final OAuth2Exception e) {
|
||||
throw new BadCredentialsException("Could not obtain access token", e);
|
||||
}
|
||||
try {
|
||||
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
|
||||
String kid = JwtHelper.headers(idToken)
|
||||
.get("kid");
|
||||
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
|
||||
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
|
||||
verifyClaims(authInfo);
|
||||
final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
|
||||
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||
} catch (final Exception e) {
|
||||
throw new BadCredentialsException("Could not obtain user details from token", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void verifyClaims(Map claims) {
|
||||
int exp = (int) claims.get("exp");
|
||||
Date expireDate = new Date(exp * 1000L);
|
||||
Date now = new Date();
|
||||
if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
|
||||
throw new RuntimeException("Invalid claims");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private RsaVerifier verifier(String kid) throws Exception {
|
||||
JwkProvider provider = new UrlJwkProvider(new URL(jwkUrl));
|
||||
Jwk jwk = provider.get(kid);
|
||||
return new RsaVerifier((RSAPublicKey) jwk.getPublicKey());
|
||||
}
|
||||
|
||||
public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
|
||||
restTemplate = restTemplate2;
|
||||
|
||||
}
|
||||
|
||||
private static class NoopAuthenticationManager implements AuthenticationManager {
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
|
||||
public class OpenIdConnectUserDetails implements UserDetails {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String userId;
|
||||
private String username;
|
||||
private OAuth2AccessToken token;
|
||||
|
||||
public OpenIdConnectUserDetails(Map<String, String> userInfo, OAuth2AccessToken token) {
|
||||
this.userId = userInfo.get("sub");
|
||||
this.username = userInfo.get("email");
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public OAuth2AccessToken getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(OAuth2AccessToken token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
server.port=8081
|
||||
google.clientId=TODO
|
||||
google.clientSecret=TODO
|
||||
google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token
|
||||
google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth
|
||||
google.redirectUri=http://localhost:8081/google-login
|
||||
google.issuer=accounts.google.com
|
||||
google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.baeldung.config.SpringOpenidApplication;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = SpringOpenidApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user