diff --git a/spring-security-oauth/pom.xml b/spring-security-oauth/pom.xml index 839858f12f..01ab77afc0 100644 --- a/spring-security-oauth/pom.xml +++ b/spring-security-oauth/pom.xml @@ -21,7 +21,11 @@ spring-security-config ${org.springframework.security.version} - + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + org.springframework.security.oauth spring-security-oauth2 @@ -152,6 +156,7 @@ runtime + diff --git a/spring-security-oauth/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-oauth/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..9eaa8097b4 --- /dev/null +++ b/spring-security-oauth/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,41 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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.web.authentication.LoginUrlAuthenticationEntryPoint; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/","/login").permitAll() + .anyRequest().hasRole("USER") + .and() + .httpBasic().authenticationEntryPoint(oauth2AuthenticationEntryPoint()); + + // @formatter:on + } + + private LoginUrlAuthenticationEntryPoint oauth2AuthenticationEntryPoint() { + return new LoginUrlAuthenticationEntryPoint("/login"); + } + +} diff --git a/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java b/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java index 6887a174b6..79508f8ca1 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java @@ -25,6 +25,7 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -42,7 +43,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; @@ -53,13 +54,20 @@ public class WebConfig extends WebMvcConfigurerAdapter { configurer.enable(); } + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/home.html"); + } + @Bean public ScheduledTasks scheduledTasks(OAuth2ProtectedResourceDetails reddit) { - ScheduledTasks s = new ScheduledTasks(); + final ScheduledTasks s = new ScheduledTasks(); s.setRedditRestTemplate(new OAuth2RestTemplate(reddit)); return s; } + @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @@ -83,7 +91,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Bean public OAuth2ProtectedResourceDetails reddit() { - AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); + final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); details.setId("reddit"); details.setClientId(clientID); details.setClientSecret(clientSecret); @@ -92,13 +100,15 @@ public class WebConfig extends WebMvcConfigurerAdapter { details.setTokenName("oauth_token"); details.setScope(Arrays.asList("identity", "read", "submit")); details.setGrantType("authorization_code"); + details.setPreEstablishedRedirectUri("http://localhost:8080/spring-security-oauth/login"); + details.setUseCurrentUri(false); return details; } @Bean public OAuth2RestTemplate redditRestTemplate(OAuth2ClientContext clientContext) { - OAuth2RestTemplate template = new OAuth2RestTemplate(reddit(), clientContext); - AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays. asList(new MyAuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(), new ResourceOwnerPasswordAccessTokenProvider(), + final OAuth2RestTemplate template = new OAuth2RestTemplate(reddit(), clientContext); + final AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays. asList(new MyAuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(), new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider())); template.setAccessTokenProvider(accessTokenProvider); return template; diff --git a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java index ea0bc140bd..48cca622b6 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java +++ b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java @@ -2,13 +2,12 @@ package org.baeldung.web; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpSession; - import org.baeldung.persistence.dao.PostRepository; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.Post; @@ -18,6 +17,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.stereotype.Controller; @@ -48,13 +50,12 @@ public class RedditController { @Autowired private PostRepository postReopsitory; - @RequestMapping("/info") - public final String getInfo(HttpSession session) { + @RequestMapping("/login") + public final String redditLogin() { final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/v1/me", JsonNode.class); - final String name = node.get("name").asText(); - addUser(name, redditRestTemplate.getAccessToken()); - session.setAttribute("username", name); - return "reddit"; + loadAuthentication(node.get("name").asText(), redditRestTemplate.getAccessToken()); + System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()); + return "redirect:home.html"; } @RequestMapping(value = "/submit", method = RequestMethod.POST) @@ -71,6 +72,8 @@ public class RedditController { @RequestMapping("/post") public final String showSubmissionForm(final Model model) { + System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()); + final boolean isCaptchaNeeded = getCurrentUser().isCaptchaNeeded(); if (isCaptchaNeeded) { final String iden = getNewCaptcha(); @@ -207,25 +210,26 @@ public class RedditController { } } - private final void addUser(final String name, final OAuth2AccessToken token) { + private final void loadAuthentication(final String name, final OAuth2AccessToken token) { User user = userReopsitory.findByUsername(name); if (user == null) { user = new User(); user.setUsername(name); - user.setAccessToken(token.getValue()); - user.setRefreshToken(token.getRefreshToken().getValue()); - user.setTokenExpiration(token.getExpiration()); } - final String needsCaptchaResult = needsCaptcha(); - if (needsCaptchaResult.equalsIgnoreCase("true")) { + if (needsCaptcha().equalsIgnoreCase("true")) { user.setNeedCaptcha(true); } else { user.setNeedCaptcha(false); } + user.setAccessToken(token.getValue()); user.setRefreshToken(token.getRefreshToken().getValue()); + user.setTokenExpiration(token.getExpiration()); userReopsitory.save(user); + + final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, token.getValue(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + SecurityContextHolder.getContext().setAuthentication(auth); } } diff --git a/spring-security-oauth/src/main/webapp/WEB-INF/jsp/editPostForm.jsp b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/editPostForm.jsp index cba3d66977..ab794aa8ca 100755 --- a/spring-security-oauth/src/main/webapp/WEB-INF/jsp/editPostForm.jsp +++ b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/editPostForm.jsp @@ -23,20 +23,14 @@ border-color: #ddd;