JAVA-12732: rename spring-5-security-oauth to spring-security-oauth2
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:jersey-application.properties")
|
||||
public class JerseyApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JerseyApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
|
||||
@Path("/")
|
||||
public class JerseyResource {
|
||||
@GET
|
||||
@Path("login")
|
||||
@Produces(MediaType.TEXT_HTML)
|
||||
public String login() {
|
||||
return "Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>";
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.TEXT_PLAIN)
|
||||
public String home(@Context SecurityContext securityContext) {
|
||||
OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) securityContext.getUserPrincipal();
|
||||
OAuth2AuthenticatedPrincipal authenticatedPrincipal = authenticationToken.getPrincipal();
|
||||
String userName = authenticatedPrincipal.getAttribute("login");
|
||||
return "Hello " + userName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.jersey;
|
||||
|
||||
import org.glassfish.jersey.server.ResourceConfig;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class RestConfig extends ResourceConfig {
|
||||
public RestConfig() {
|
||||
register(JerseyResource.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.jersey;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/login")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/login");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.oauth2;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.converter.FormHttpMessageConverter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
|
||||
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.oauth2request.CustomAuthorizationRequestResolver;
|
||||
import com.baeldung.oauth2request.CustomRequestEntityConverter;
|
||||
import com.baeldung.oauth2request.CustomTokenResponseConverter;
|
||||
|
||||
//@Configuration
|
||||
@PropertySource("application-oauth2.properties")
|
||||
public class CustomRequestSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/oauth_login", "/loginFailure", "/")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/oauth_login")
|
||||
.authorizationEndpoint()
|
||||
.authorizationRequestResolver( new CustomAuthorizationRequestResolver(clientRegistrationRepository(),"/oauth2/authorize-client"))
|
||||
|
||||
.baseUri("/oauth2/authorize-client")
|
||||
.authorizationRequestRepository(authorizationRequestRepository())
|
||||
.and()
|
||||
.tokenEndpoint()
|
||||
.accessTokenResponseClient(accessTokenResponseClient())
|
||||
.and()
|
||||
.defaultSuccessUrl("/loginSuccess")
|
||||
.failureUrl("/loginFailure");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
|
||||
return new HttpSessionOAuth2AuthorizationRequestRepository();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
|
||||
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
|
||||
accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter());
|
||||
|
||||
OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter();
|
||||
tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomTokenResponseConverter());
|
||||
RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter));
|
||||
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
|
||||
accessTokenResponseClient.setRestOperations(restTemplate);
|
||||
return accessTokenResponseClient;
|
||||
}
|
||||
|
||||
|
||||
// additional configuration for non-Spring Boot projects
|
||||
private static List<String> clients = Arrays.asList("google", "facebook");
|
||||
|
||||
//@Bean
|
||||
public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
List<ClientRegistration> registrations = clients.stream()
|
||||
.map(c -> getRegistration(c))
|
||||
.filter(registration -> registration != null)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new InMemoryClientRegistrationRepository(registrations);
|
||||
}
|
||||
|
||||
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
private ClientRegistration getRegistration(String client) {
|
||||
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
|
||||
|
||||
if (clientId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
|
||||
if (client.equals("google")) {
|
||||
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
}
|
||||
if (client.equals("facebook")) {
|
||||
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.oauth2;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Controller
|
||||
public class LoginController {
|
||||
|
||||
private static final String authorizationRequestBaseUri = "oauth2/authorize-client";
|
||||
Map<String, String> oauth2AuthenticationUrls = new HashMap<>();
|
||||
|
||||
@Autowired
|
||||
private ClientRegistrationRepository clientRegistrationRepository;
|
||||
@Autowired
|
||||
private OAuth2AuthorizedClientService authorizedClientService;
|
||||
|
||||
@GetMapping("/oauth_login")
|
||||
public String getLoginPage(Model model) {
|
||||
Iterable<ClientRegistration> clientRegistrations = null;
|
||||
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository)
|
||||
.as(Iterable.class);
|
||||
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
|
||||
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
|
||||
}
|
||||
|
||||
clientRegistrations.forEach(registration -> oauth2AuthenticationUrls.put(registration.getClientName(), authorizationRequestBaseUri + "/" + registration.getRegistrationId()));
|
||||
model.addAttribute("urls", oauth2AuthenticationUrls);
|
||||
|
||||
return "oauth_login";
|
||||
}
|
||||
|
||||
@GetMapping("/loginSuccess")
|
||||
public String getLoginInfo(Model model, OAuth2AuthenticationToken authentication) {
|
||||
|
||||
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());
|
||||
|
||||
String userInfoEndpointUri = client.getClientRegistration()
|
||||
.getProviderDetails()
|
||||
.getUserInfoEndpoint()
|
||||
.getUri();
|
||||
|
||||
if (!StringUtils.isEmpty(userInfoEndpointUri)) {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken()
|
||||
.getTokenValue());
|
||||
|
||||
HttpEntity<String> entity = new HttpEntity<String>("", headers);
|
||||
|
||||
ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class);
|
||||
Map userAttributes = response.getBody();
|
||||
model.addAttribute("name", userAttributes.get("name"));
|
||||
}
|
||||
|
||||
return "loginSuccess";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.oauth2;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("securedPage");
|
||||
registry.addViewController("loginFailure");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.oauth2;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
|
||||
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
|
||||
@Configuration
|
||||
@PropertySource("application-oauth2.properties")
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/oauth_login", "/loginFailure", "/")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/oauth_login")
|
||||
.authorizationEndpoint()
|
||||
.baseUri("/oauth2/authorize-client")
|
||||
.authorizationRequestRepository(authorizationRequestRepository())
|
||||
.and()
|
||||
.tokenEndpoint()
|
||||
.accessTokenResponseClient(accessTokenResponseClient())
|
||||
.and()
|
||||
.defaultSuccessUrl("/loginSuccess")
|
||||
.failureUrl("/loginFailure");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
|
||||
return new HttpSessionOAuth2AuthorizationRequestRepository();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
|
||||
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
|
||||
return accessTokenResponseClient;
|
||||
}
|
||||
|
||||
// additional configuration for non-Spring Boot projects
|
||||
private static List<String> clients = Arrays.asList("google", "facebook");
|
||||
|
||||
// @Bean
|
||||
public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
List<ClientRegistration> registrations = clients.stream()
|
||||
.map(c -> getRegistration(c))
|
||||
.filter(registration -> registration != null)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new InMemoryClientRegistrationRepository(registrations);
|
||||
}
|
||||
|
||||
// @Bean
|
||||
public OAuth2AuthorizedClientService authorizedClientService() {
|
||||
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository());
|
||||
}
|
||||
|
||||
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
private ClientRegistration getRegistration(String client) {
|
||||
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
|
||||
|
||||
if (clientId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
|
||||
if (client.equals("google")) {
|
||||
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
}
|
||||
if (client.equals("facebook")) {
|
||||
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.oauth2;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@PropertySource("classpath:default-application.properties")
|
||||
@SpringBootApplication
|
||||
public class SpringOAuthApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringOAuthApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.oauth2extractors;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.AbstractEnvironment;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@PropertySource("classpath:default-application.properties")
|
||||
@SpringBootApplication
|
||||
@Controller
|
||||
public class ExtractorsApplication {
|
||||
public static void main(String[] args) {
|
||||
if (Strings.isEmpty(System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME))) {
|
||||
/*System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
|
||||
"oauth2-extractors-baeldung");*/
|
||||
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
|
||||
"oauth2-extractors-github");
|
||||
}
|
||||
|
||||
SpringApplication.run(ExtractorsApplication.class, args);
|
||||
}
|
||||
|
||||
@RequestMapping("/")
|
||||
public String index() {
|
||||
return "oauth2_extractors";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.oauth2extractors.configuration;
|
||||
|
||||
import com.baeldung.oauth2extractors.extractor.custom.BaeldungAuthoritiesExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.custom.BaeldungPrincipalExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.github.GithubAuthoritiesExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.github.GithubPrincipalExtractor;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableOAuth2Sso
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/**")
|
||||
.authorizeRequests()
|
||||
.antMatchers("/login**")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.formLogin().disable();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-baeldung")
|
||||
public PrincipalExtractor baeldungPrincipalExtractor() {
|
||||
return new BaeldungPrincipalExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-baeldung")
|
||||
public AuthoritiesExtractor baeldungAuthoritiesExtractor() {
|
||||
return new BaeldungAuthoritiesExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-github")
|
||||
public PrincipalExtractor githubPrincipalExtractor() {
|
||||
return new GithubPrincipalExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-github")
|
||||
public AuthoritiesExtractor githubAuthoritiesExtractor() {
|
||||
return new GithubAuthoritiesExtractor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.oauth2extractors.extractor.custom;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BaeldungAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||
|
||||
@Override
|
||||
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
|
||||
return AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList(asAuthorities(map));
|
||||
}
|
||||
|
||||
private String asAuthorities(Map<String, Object> map) {
|
||||
List<String> authorities = new ArrayList<>();
|
||||
authorities.add("BAELDUNG_USER");
|
||||
List<LinkedHashMap<String, String>> authz = (List<LinkedHashMap<String, String>>) map.get("authorities");
|
||||
for (LinkedHashMap<String, String> entry : authz) {
|
||||
authorities.add(entry.get("authority"));
|
||||
}
|
||||
return String.join(",", authorities);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.oauth2extractors.extractor.custom;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class BaeldungPrincipalExtractor implements PrincipalExtractor {
|
||||
|
||||
@Override
|
||||
public Object extractPrincipal(Map<String, Object> map) {
|
||||
return map.get("name");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.oauth2extractors.extractor.github;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public class GithubAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||
private List<GrantedAuthority> GITHUB_FREE_AUTHORITIES = AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE");
|
||||
private List<GrantedAuthority> GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED");
|
||||
|
||||
@Override
|
||||
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
|
||||
if (Objects.nonNull(map.get("plan"))) {
|
||||
if (!((LinkedHashMap) map.get("plan"))
|
||||
.get("name")
|
||||
.equals("free")) {
|
||||
return GITHUB_SUBSCRIBED_AUTHORITIES;
|
||||
}
|
||||
}
|
||||
return GITHUB_FREE_AUTHORITIES;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.oauth2extractors.extractor.github;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class GithubPrincipalExtractor implements PrincipalExtractor {
|
||||
|
||||
@Override
|
||||
public Object extractPrincipal(Map<String, Object> map) {
|
||||
return map.get("login");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.oauth2request;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
|
||||
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
|
||||
|
||||
private OAuth2AuthorizationRequestResolver defaultResolver;
|
||||
|
||||
public CustomAuthorizationRequestResolver(ClientRegistrationRepository repo, String authorizationRequestBaseUri){
|
||||
defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(repo, authorizationRequestBaseUri);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
|
||||
OAuth2AuthorizationRequest req = defaultResolver.resolve(request);
|
||||
if(req != null){
|
||||
req = customizeAuthorizationRequest(req);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) {
|
||||
OAuth2AuthorizationRequest req = defaultResolver.resolve(request, clientRegistrationId);
|
||||
if(req != null){
|
||||
req = customizeAuthorizationRequest(req);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req) {
|
||||
Map<String,Object> extraParams = new HashMap<String,Object>();
|
||||
extraParams.putAll(req.getAdditionalParameters()); //VIP note
|
||||
extraParams.put("test", "extra");
|
||||
System.out.println("here =====================");
|
||||
return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build();
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequest customizeAuthorizationRequest1(OAuth2AuthorizationRequest req) {
|
||||
return OAuth2AuthorizationRequest.from(req).state("xyz").build();
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequest customizeOktaReq(OAuth2AuthorizationRequest req) {
|
||||
Map<String,Object> extraParams = new HashMap<String,Object>();
|
||||
extraParams.putAll(req.getAdditionalParameters());
|
||||
extraParams.put("idp", "https://idprovider.com");
|
||||
return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.oauth2request;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.http.RequestEntity;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequestEntityConverter;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
public class CustomRequestEntityConverter implements Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> {
|
||||
|
||||
private OAuth2AuthorizationCodeGrantRequestEntityConverter defaultConverter;
|
||||
|
||||
public CustomRequestEntityConverter() {
|
||||
defaultConverter = new OAuth2AuthorizationCodeGrantRequestEntityConverter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest req) {
|
||||
RequestEntity<?> entity = defaultConverter.convert(req);
|
||||
MultiValueMap<String, String> params = (MultiValueMap<String,String>) entity.getBody();
|
||||
params.add("test2", "extra2");
|
||||
System.out.println(params.entrySet());
|
||||
return new RequestEntity<>(params, entity.getHeaders(), entity.getMethod(), entity.getUrl());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.oauth2request;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class CustomTokenResponseConverter implements Converter<Map<String, String>, OAuth2AccessTokenResponse> {
|
||||
private static final Set<String> TOKEN_RESPONSE_PARAMETER_NAMES = Stream.of(
|
||||
OAuth2ParameterNames.ACCESS_TOKEN,
|
||||
OAuth2ParameterNames.TOKEN_TYPE,
|
||||
OAuth2ParameterNames.EXPIRES_IN,
|
||||
OAuth2ParameterNames.REFRESH_TOKEN,
|
||||
OAuth2ParameterNames.SCOPE) .collect(Collectors.toSet());
|
||||
|
||||
@Override
|
||||
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
|
||||
String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
|
||||
|
||||
OAuth2AccessToken.TokenType accessTokenType = null;
|
||||
if (OAuth2AccessToken.TokenType.BEARER.getValue()
|
||||
.equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) {
|
||||
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
|
||||
}
|
||||
|
||||
long expiresIn = 0;
|
||||
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
|
||||
try {
|
||||
expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
|
||||
} catch (NumberFormatException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> scopes = Collections.emptySet();
|
||||
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
|
||||
String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
|
||||
scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " "))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
String refreshToken = tokenResponseParameters.get(OAuth2ParameterNames.REFRESH_TOKEN);
|
||||
|
||||
Map<String, Object> additionalParameters = new LinkedHashMap<>();
|
||||
tokenResponseParameters.entrySet()
|
||||
.stream()
|
||||
.filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
|
||||
.forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));
|
||||
|
||||
return OAuth2AccessTokenResponse.withToken(accessToken)
|
||||
.tokenType(accessTokenType)
|
||||
.expiresIn(expiresIn)
|
||||
.scopes(scopes)
|
||||
.refreshToken(refreshToken)
|
||||
.additionalParameters(additionalParameters)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.oauth2request;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
|
||||
public class LinkedinTokenResponseConverter implements Converter<Map<String, String>, OAuth2AccessTokenResponse> {
|
||||
|
||||
@Override
|
||||
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
|
||||
String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
|
||||
long expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
|
||||
|
||||
OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;
|
||||
|
||||
return OAuth2AccessTokenResponse.withToken(accessToken)
|
||||
.tokenType(accessTokenType)
|
||||
.expiresIn(expiresIn)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.oauth2resttemplate;
|
||||
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Collection;
|
||||
|
||||
@Controller
|
||||
public class AppController {
|
||||
|
||||
OAuth2RestTemplate restTemplate;
|
||||
|
||||
public AppController(OAuth2RestTemplate restTemplate) {
|
||||
this.restTemplate = restTemplate;
|
||||
}
|
||||
|
||||
@GetMapping("/home")
|
||||
public String welcome(Model model, Principal principal) {
|
||||
model.addAttribute("name", principal.getName());
|
||||
return "home";
|
||||
}
|
||||
|
||||
@GetMapping("/repos")
|
||||
public String repos(Model model) {
|
||||
Collection<GithubRepo> repos = restTemplate.getForObject("https://api.github.com/user/repos", Collection.class);
|
||||
model.addAttribute("repos", repos);
|
||||
return "repositories";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.oauth2resttemplate;
|
||||
|
||||
public class GithubRepo {
|
||||
Long id;
|
||||
String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.oauth2resttemplate;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.client.OAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
|
||||
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
|
||||
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
@Configuration
|
||||
@EnableOAuth2Client
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
OAuth2ClientContext oauth2ClientContext;
|
||||
|
||||
public SecurityConfig(OAuth2ClientContext oauth2ClientContext) {
|
||||
this.oauth2ClientContext = oauth2ClientContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests().antMatchers("/", "/login**", "/error**")
|
||||
.permitAll().anyRequest().authenticated()
|
||||
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
|
||||
.and().addFilterBefore(oauth2ClientFilter(), BasicAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
|
||||
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<>();
|
||||
registration.setFilter(filter);
|
||||
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2RestTemplate restTemplate() {
|
||||
return new OAuth2RestTemplate(githubClient(), oauth2ClientContext);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties("github.client")
|
||||
public AuthorizationCodeResourceDetails githubClient() {
|
||||
return new AuthorizationCodeResourceDetails();
|
||||
}
|
||||
|
||||
private Filter oauth2ClientFilter() {
|
||||
OAuth2ClientAuthenticationProcessingFilter oauth2ClientFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github");
|
||||
OAuth2RestTemplate restTemplate = restTemplate();
|
||||
oauth2ClientFilter.setRestTemplate(restTemplate);
|
||||
UserInfoTokenServices tokenServices = new UserInfoTokenServices(githubResource().getUserInfoUri(), githubClient().getClientId());
|
||||
tokenServices.setRestTemplate(restTemplate);
|
||||
oauth2ClientFilter.setTokenServices(tokenServices);
|
||||
return oauth2ClientFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties("github.resource")
|
||||
public ResourceServerProperties githubResource() {
|
||||
return new ResourceServerProperties();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.oauth2resttemplate;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:application-oauth2-rest-template.properties")
|
||||
public class SpringSecurityOauth2ClientApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringSecurityOauth2ClientApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
server.port=8082
|
||||
security.oauth2.client.client-id=SampleClientId
|
||||
security.oauth2.client.client-secret=secret
|
||||
security.oauth2.client.access-token-uri=http://localhost:8081/auth/oauth/token
|
||||
security.oauth2.client.user-authorization-uri=http://localhost:8081/auth/oauth/authorize
|
||||
security.oauth2.resource.user-info-uri=http://localhost:8081/auth/user/me
|
||||
@@ -0,0 +1,7 @@
|
||||
server.port=8082
|
||||
security.oauth2.client.client-id=89a7c4facbb3434d599d
|
||||
security.oauth2.client.client-secret=9b3b08e4a340bd20e866787e4645b54f73d74b6a
|
||||
security.oauth2.client.access-token-uri=https://github.com/login/oauth/access_token
|
||||
security.oauth2.client.user-authorization-uri=https://github.com/login/oauth/authorize
|
||||
security.oauth2.client.scope=read:user,user:email
|
||||
security.oauth2.resource.user-info-uri=https://api.github.com/user
|
||||
@@ -0,0 +1,9 @@
|
||||
github.client.clientId=[CLIENT_ID]
|
||||
github.client.clientSecret=[CLIENT_SECRET]
|
||||
github.client.userAuthorizationUri=https://github.com/login/oauth/authorize
|
||||
github.client.accessTokenUri=https://github.com/login/oauth/access_token
|
||||
github.client.clientAuthenticationScheme=form
|
||||
|
||||
github.resource.userInfoUri=https://api.github.com/user
|
||||
|
||||
spring.thymeleaf.prefix=classpath:/templates/oauth2resttemplate/
|
||||
@@ -0,0 +1,5 @@
|
||||
spring.security.oauth2.client.registration.google.client-id=368238083842-3d4gc7p54rs6bponn0qhn4nmf6apf24a.apps.googleusercontent.com
|
||||
spring.security.oauth2.client.registration.google.client-secret=2RM2QkEaf3A8-iCNqSfdG8wP
|
||||
|
||||
spring.security.oauth2.client.registration.facebook.client-id=151640435578187
|
||||
spring.security.oauth2.client.registration.facebook.client-secret=3724fb293d401245b1ce7b2d70e97571
|
||||
@@ -0,0 +1,3 @@
|
||||
logging.level.root=INFO
|
||||
|
||||
logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG
|
||||
@@ -0,0 +1 @@
|
||||
server.port=8081
|
||||
@@ -0,0 +1,3 @@
|
||||
server.port=8083
|
||||
spring.security.oauth2.client.registration.github.client-id=<your-client-id>
|
||||
spring.security.oauth2.client.registration.github.client-secret=<your-client-secret>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,8 @@
|
||||
p.error {
|
||||
font-weight: bold;
|
||||
color: red;
|
||||
}
|
||||
|
||||
div.logout {
|
||||
margin-right: 2em;;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
Home
|
||||
Welcome!
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Login Failure</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
Login Failure
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Login Success</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<link rel="stylesheet"
|
||||
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
<h3>
|
||||
<div class="label label-info">
|
||||
Welcome, <span th:text="${name}">user</span>!
|
||||
</div>
|
||||
</h3>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<title>Spring Security Principal and Authorities extractor</title>
|
||||
<link rel="stylesheet"
|
||||
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="col-sm-12">
|
||||
<h1>Secured Page</h1>
|
||||
Authenticated username:
|
||||
<div th:text="${#authentication.name}"></div>
|
||||
Authorities:
|
||||
<div th:text="${#authentication.authorities}"></div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,9 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Error</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>An error occurred.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Home</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
Welcome <b th:inline="text"> [[${name}]] </b>
|
||||
</p>
|
||||
<h3>
|
||||
<a href="/repos">View Repositories</a><br/><br/>
|
||||
</h3>
|
||||
|
||||
<form th:action="@{/logout}" method="POST">
|
||||
<input type="submit" value="Logout"/>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>OAuth2Client</title>
|
||||
</head>
|
||||
<body>
|
||||
<h3>
|
||||
<a href="/home" th:href="@{/home}" th:if="${#httpServletRequest?.remoteUser != undefined }">
|
||||
Go to Home
|
||||
</a>
|
||||
<a href="/login/github" th:href="@{/login/github}" th:if="${#httpServletRequest?.remoteUser == undefined }">
|
||||
GitHub Login
|
||||
</a>
|
||||
</h3>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Repositories</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
<h2>Repos</h2>
|
||||
</p>
|
||||
<ul th:each="repo: ${repos}">
|
||||
<li th:text="${repo.name}"></li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Oauth2 Login</title>
|
||||
<link rel="stylesheet"
|
||||
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="col-sm-3 well">
|
||||
<h3>Login with:</h3>
|
||||
<div class="list-group">
|
||||
<p th:each="url : ${urls}">
|
||||
<a th:text="${url.key}" th:href="${url.value}" class="list-group-item active">Client</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
<title>Secured Page</title>
|
||||
</head>
|
||||
<body>
|
||||
Secured Page - Welcome
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.jersey;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
import static org.springframework.http.MediaType.TEXT_HTML;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT)
|
||||
@TestPropertySource(properties = "spring.security.oauth2.client.registration.github.client-id:test-id")
|
||||
public class JerseyResourceUnitTest {
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
private String basePath;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
basePath = "http://localhost:" + port + "/";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserIsUnauthenticated_thenTheyAreRedirectedToLoginPage() {
|
||||
ResponseEntity<Object> response = restTemplate.getForEntity(basePath, Object.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(response.getBody()).isNull();
|
||||
|
||||
URI redirectLocation = response.getHeaders().getLocation();
|
||||
assertThat(redirectLocation).isNotNull();
|
||||
assertThat(redirectLocation.toString()).isEqualTo(basePath + "login");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserAttemptsToLogin_thenAuthorizationPathIsReturned() {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "login", String.class);
|
||||
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML);
|
||||
assertThat(response.getBody()).isEqualTo("Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserAccessesAuthorizationEndpoint_thenTheyAresRedirectedToProvider() {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "oauth2/authorization/github", String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(response.getBody()).isNull();
|
||||
|
||||
URI redirectLocation = response.getHeaders().getLocation();
|
||||
assertThat(redirectLocation).isNotNull();
|
||||
assertThat(redirectLocation.getHost()).isEqualTo("github.com");
|
||||
assertThat(redirectLocation.getPath()).isEqualTo("/login/oauth/authorize");
|
||||
|
||||
String redirectionQuery = redirectLocation.getQuery();
|
||||
assertThat(redirectionQuery.contains("response_type=code"));
|
||||
assertThat(redirectionQuery.contains("client_id=test-id"));
|
||||
assertThat(redirectionQuery.contains("scope=read:user"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.oauth2extractors;
|
||||
|
||||
import com.baeldung.oauth2extractors.configuration.SecurityConfig;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ExtractorsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@ContextConfiguration(classes = {SecurityConfig.class})
|
||||
@ActiveProfiles("oauth2-extractors-github")
|
||||
public class ExtractorsUnitTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.addFilters(springSecurityFilterChain)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidRequestWithoutAuthentication_shouldFailWith302() throws Exception {
|
||||
mvc
|
||||
.perform(get("/"))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user