Skip to content

Commit 167d452

Browse files
committed
modify reddit authentication
1 parent 7724bd2 commit 167d452

11 files changed

Lines changed: 116 additions & 85 deletions

File tree

‎spring-security-oauth/pom.xml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@
2121
<artifactId>spring-security-config</artifactId>
2222
<version>${org.springframework.security.version}</version>
2323
</dependency>
24-
24+
<dependency>
25+
<groupId>org.springframework.security</groupId>
26+
<artifactId>spring-security-taglibs</artifactId>
27+
<version>${org.springframework.security.version}</version>
28+
</dependency>
2529
<dependency>
2630
<groupId>org.springframework.security.oauth</groupId>
2731
<artifactId>spring-security-oauth2</artifactId>
@@ -152,6 +156,7 @@
152156
<scope>runtime</scope>
153157
</dependency>
154158

159+
155160
<!-- marshalling -->
156161

157162
<dependency>
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
5+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
6+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
10+
11+
@Configuration
12+
@EnableWebSecurity
13+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
14+
15+
@Override
16+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
17+
auth.inMemoryAuthentication();
18+
}
19+
20+
@Override
21+
public void configure(WebSecurity web) throws Exception {
22+
web.ignoring().antMatchers("/resources/**");
23+
}
24+
25+
@Override
26+
protected void configure(HttpSecurity http) throws Exception {
27+
// @formatter:off
28+
http.authorizeRequests()
29+
.antMatchers("/","/login").permitAll()
30+
.anyRequest().hasRole("USER")
31+
.and()
32+
.httpBasic().authenticationEntryPoint(oauth2AuthenticationEntryPoint());
33+
34+
// @formatter:on
35+
}
36+
37+
private LoginUrlAuthenticationEntryPoint oauth2AuthenticationEntryPoint() {
38+
return new LoginUrlAuthenticationEntryPoint("/login");
39+
}
40+
41+
}

‎spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
2626
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
2727
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
28+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
2829
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
2930
import org.springframework.web.servlet.view.InternalResourceViewResolver;
3031

@@ -42,7 +43,7 @@ public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderCon
4243

4344
@Bean
4445
public ViewResolver viewResolver() {
45-
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
46+
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
4647
viewResolver.setPrefix("/WEB-INF/jsp/");
4748
viewResolver.setSuffix(".jsp");
4849
return viewResolver;
@@ -53,13 +54,20 @@ public void configureDefaultServletHandling(DefaultServletHandlerConfigurer conf
5354
configurer.enable();
5455
}
5556

57+
@Override
58+
public void addViewControllers(final ViewControllerRegistry registry) {
59+
super.addViewControllers(registry);
60+
registry.addViewController("/home.html");
61+
}
62+
5663
@Bean
5764
public ScheduledTasks scheduledTasks(OAuth2ProtectedResourceDetails reddit) {
58-
ScheduledTasks s = new ScheduledTasks();
65+
final ScheduledTasks s = new ScheduledTasks();
5966
s.setRedditRestTemplate(new OAuth2RestTemplate(reddit));
6067
return s;
6168
}
6269

70+
@Override
6371
public void addResourceHandlers(ResourceHandlerRegistry registry) {
6472
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
6573
}
@@ -83,7 +91,7 @@ protected static class ResourceConfiguration {
8391

8492
@Bean
8593
public OAuth2ProtectedResourceDetails reddit() {
86-
AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
94+
final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
8795
details.setId("reddit");
8896
details.setClientId(clientID);
8997
details.setClientSecret(clientSecret);
@@ -92,13 +100,15 @@ public OAuth2ProtectedResourceDetails reddit() {
92100
details.setTokenName("oauth_token");
93101
details.setScope(Arrays.asList("identity", "read", "submit"));
94102
details.setGrantType("authorization_code");
103+
details.setPreEstablishedRedirectUri("http://localhost:8080/spring-security-oauth/login");
104+
details.setUseCurrentUri(false);
95105
return details;
96106
}
97107

98108
@Bean
99109
public OAuth2RestTemplate redditRestTemplate(OAuth2ClientContext clientContext) {
100-
OAuth2RestTemplate template = new OAuth2RestTemplate(reddit(), clientContext);
101-
AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider> asList(new MyAuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(), new ResourceOwnerPasswordAccessTokenProvider(),
110+
final OAuth2RestTemplate template = new OAuth2RestTemplate(reddit(), clientContext);
111+
final AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider> asList(new MyAuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(), new ResourceOwnerPasswordAccessTokenProvider(),
102112
new ClientCredentialsAccessTokenProvider()));
103113
template.setAccessTokenProvider(accessTokenProvider);
104114
return template;

‎spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22

33
import java.text.ParseException;
44
import java.text.SimpleDateFormat;
5+
import java.util.Arrays;
56
import java.util.Date;
67
import java.util.HashMap;
78
import java.util.List;
89
import java.util.Map;
910

10-
import javax.servlet.http.HttpSession;
11-
1211
import org.baeldung.persistence.dao.PostRepository;
1312
import org.baeldung.persistence.dao.UserRepository;
1413
import org.baeldung.persistence.model.Post;
@@ -18,6 +17,9 @@
1817
import org.slf4j.LoggerFactory;
1918
import org.springframework.beans.factory.annotation.Autowired;
2019
import org.springframework.http.HttpStatus;
20+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
21+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
22+
import org.springframework.security.core.context.SecurityContextHolder;
2123
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
2224
import org.springframework.security.oauth2.common.OAuth2AccessToken;
2325
import org.springframework.stereotype.Controller;
@@ -48,13 +50,12 @@ public class RedditController {
4850
@Autowired
4951
private PostRepository postReopsitory;
5052

51-
@RequestMapping("/info")
52-
public final String getInfo(HttpSession session) {
53+
@RequestMapping("/login")
54+
public final String redditLogin() {
5355
final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/v1/me", JsonNode.class);
54-
final String name = node.get("name").asText();
55-
addUser(name, redditRestTemplate.getAccessToken());
56-
session.setAttribute("username", name);
57-
return "reddit";
56+
loadAuthentication(node.get("name").asText(), redditRestTemplate.getAccessToken());
57+
System.out.println(SecurityContextHolder.getContext().getAuthentication().toString());
58+
return "redirect:home.html";
5859
}
5960

6061
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@@ -71,6 +72,8 @@ public final String submit(final Model model, @RequestParam final Map<String, St
7172

7273
@RequestMapping("/post")
7374
public final String showSubmissionForm(final Model model) {
75+
System.out.println(SecurityContextHolder.getContext().getAuthentication().toString());
76+
7477
final boolean isCaptchaNeeded = getCurrentUser().isCaptchaNeeded();
7578
if (isCaptchaNeeded) {
7679
final String iden = getNewCaptcha();
@@ -207,25 +210,26 @@ private final String parseResponse(final JsonNode node) {
207210
}
208211
}
209212

210-
private final void addUser(final String name, final OAuth2AccessToken token) {
213+
private final void loadAuthentication(final String name, final OAuth2AccessToken token) {
211214
User user = userReopsitory.findByUsername(name);
212215
if (user == null) {
213216
user = new User();
214217
user.setUsername(name);
215-
user.setAccessToken(token.getValue());
216-
user.setRefreshToken(token.getRefreshToken().getValue());
217-
user.setTokenExpiration(token.getExpiration());
218218
}
219219

220-
final String needsCaptchaResult = needsCaptcha();
221-
if (needsCaptchaResult.equalsIgnoreCase("true")) {
220+
if (needsCaptcha().equalsIgnoreCase("true")) {
222221
user.setNeedCaptcha(true);
223222
} else {
224223
user.setNeedCaptcha(false);
225224
}
225+
226226
user.setAccessToken(token.getValue());
227227
user.setRefreshToken(token.getRefreshToken().getValue());
228+
user.setTokenExpiration(token.getExpiration());
228229
userReopsitory.save(user);
230+
231+
final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, token.getValue(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
232+
SecurityContextHolder.getContext().setAuthentication(auth);
229233
}
230234

231235
}

‎spring-security-oauth/src/main/webapp/WEB-INF/jsp/editPostForm.jsp‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,14 @@ border-color: #ddd;
2323
<body>
2424
<nav class="navbar navbar-default">
2525
<div class="container-fluid">
26-
<!-- Brand and toggle get grouped for better mobile display -->
2726
<div class="navbar-header">
28-
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
29-
<span class="sr-only">Toggle navigation</span>
30-
<span class="icon-bar"></span>
31-
<span class="icon-bar"></span>
32-
<span class="icon-bar"></span>
33-
</button>
34-
<a class="navbar-brand" href="<c:url value="/info" />">Schedule to Reddit</a>
27+
<a class="navbar-brand" href="<c:url value="/home.html" />">Schedule to Reddit</a>
3528
</div>
3629

37-
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
38-
39-
<!-- Collect the nav links, forms, and other content for toggling -->
30+
<p class="navbar-text navbar-right">Logged in as
31+
<b><sec:authentication property="principal.username" /></b>&nbsp;&nbsp;&nbsp;
32+
</p>
33+
4034
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
4135
<ul class="nav navbar-nav">
4236
<li><a href="<c:url value="/posts" />">My Scheduled Posts</a></li>

spring-security-oauth/src/main/webapp/WEB-INF/jsp/reddit.jsp renamed to spring-security-oauth/src/main/webapp/WEB-INF/jsp/home.jsp

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
2+
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
23
<html>
34
<head>
45

@@ -9,20 +10,14 @@
910
<body>
1011
<nav class="navbar navbar-default">
1112
<div class="container-fluid">
12-
<!-- Brand and toggle get grouped for better mobile display -->
1313
<div class="navbar-header">
14-
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
15-
<span class="sr-only">Toggle navigation</span>
16-
<span class="icon-bar"></span>
17-
<span class="icon-bar"></span>
18-
<span class="icon-bar"></span>
19-
</button>
2014
<a class="navbar-brand" href="#">Schedule to Reddit</a>
2115
</div>
2216

23-
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
17+
<p class="navbar-text navbar-right">Logged in as
18+
<b><sec:authentication property="principal.username" /></b>&nbsp;&nbsp;&nbsp;
19+
</p>
2420

25-
<!-- Collect the nav links, forms, and other content for toggling -->
2621
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
2722
<ul class="nav navbar-nav">
2823
<li><a href="posts">My Scheduled Posts</a></li>
@@ -34,12 +29,11 @@
3429
</div><!-- /.container-fluid -->
3530
</nav>
3631
<div class="container">
37-
<h1>Welcome, <small><c:out value="${username}"/></small></h1>
32+
<h1>Welcome, <small><sec:authentication property="principal.username" /></small></h1>
3833
<br>
3934
<a href="posts" class="btn btn-primary">My Scheduled Posts</a>
4035
<a href="post" class="btn btn-primary">Post to Reddit</a>
4136
<a href="postSchedule" class="btn btn-primary">Schedule Post to Reddit</a>
42-
4337
</div>
4438
</body>
4539
</html>

‎spring-security-oauth/src/main/webapp/WEB-INF/jsp/postListView.jsp‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
22
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
3+
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
34

45
<html>
56
<head>
@@ -11,20 +12,14 @@
1112
<body>
1213
<nav class="navbar navbar-default">
1314
<div class="container-fluid">
14-
<!-- Brand and toggle get grouped for better mobile display -->
1515
<div class="navbar-header">
16-
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
17-
<span class="sr-only">Toggle navigation</span>
18-
<span class="icon-bar"></span>
19-
<span class="icon-bar"></span>
20-
<span class="icon-bar"></span>
21-
</button>
22-
<a class="navbar-brand" href="info">Schedule to Reddit</a>
16+
<a class="navbar-brand" href="home.html">Schedule to Reddit</a>
2317
</div>
2418

25-
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
26-
27-
<!-- Collect the nav links, forms, and other content for toggling -->
19+
<p class="navbar-text navbar-right">Logged in as
20+
<b><sec:authentication property="principal.username" /></b>&nbsp;&nbsp;&nbsp;
21+
</p>
22+
2823
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
2924
<ul class="nav navbar-nav">
3025
<li class="active"><a href="posts">My Scheduled Posts</a></li>

‎spring-security-oauth/src/main/webapp/WEB-INF/jsp/schedulePostForm.jsp‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
2+
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
3+
24
<html>
35
<head>
46

@@ -23,20 +25,14 @@ border-color: #ddd;
2325
<body>
2426
<nav class="navbar navbar-default">
2527
<div class="container-fluid">
26-
<!-- Brand and toggle get grouped for better mobile display -->
2728
<div class="navbar-header">
28-
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
29-
<span class="sr-only">Toggle navigation</span>
30-
<span class="icon-bar"></span>
31-
<span class="icon-bar"></span>
32-
<span class="icon-bar"></span>
33-
</button>
34-
<a class="navbar-brand" href="info">Schedule to Reddit</a>
29+
<a class="navbar-brand" href="home.html">Schedule to Reddit</a>
3530
</div>
3631

37-
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
32+
<p class="navbar-text navbar-right">Logged in as
33+
<b><sec:authentication property="principal.username" /></b>&nbsp;&nbsp;&nbsp;
34+
</p>
3835

39-
<!-- Collect the nav links, forms, and other content for toggling -->
4036
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
4137
<ul class="nav navbar-nav">
4238
<li><a href="posts">My Scheduled Posts</a></li>

‎spring-security-oauth/src/main/webapp/WEB-INF/jsp/submissionForm.jsp‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
2+
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
3+
24
<html>
35
<head>
46

@@ -21,20 +23,14 @@ border-color: #ddd;
2123
<body>
2224
<nav class="navbar navbar-default">
2325
<div class="container-fluid">
24-
<!-- Brand and toggle get grouped for better mobile display -->
25-
<div class="navbar-header">
26-
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
27-
<span class="sr-only">Toggle navigation</span>
28-
<span class="icon-bar"></span>
29-
<span class="icon-bar"></span>
30-
<span class="icon-bar"></span>
31-
</button>
32-
<a class="navbar-brand" href="info">Schedule to Reddit</a>
26+
<div class="navbar-header">
27+
<a class="navbar-brand" href="home.html">Schedule to Reddit</a>
3328
</div>
3429

35-
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
30+
<p class="navbar-text navbar-right">Logged in as
31+
<b><sec:authentication property="principal.username" /></b>&nbsp;&nbsp;&nbsp;
32+
</p>
3633

37-
<!-- Collect the nav links, forms, and other content for toggling -->
3834
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
3935
<ul class="nav navbar-nav">
4036
<li><a href="posts">My Scheduled Posts</a></li>

0 commit comments

Comments
 (0)