Skip to content

Commit 0c63116

Browse files
committed
Add user filter to groups
1 parent cd120b6 commit 0c63116

7 files changed

Lines changed: 179 additions & 149 deletions

File tree

app/src/GroupList.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class GroupList extends Component {
7676
<div className="float-right">
7777
<Button color="success" tag={Link} to="/groups/new">Add Group</Button>
7878
</div>
79-
<h3>Java User Groups</h3>
79+
<h3>My JUG Tour</h3>
8080
<Table className="mt-4">
8181
<thead>
8282
<tr>
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.okta.developer.jugtours.config;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.security.core.Authentication;
6+
import org.springframework.security.web.DefaultRedirectStrategy;
7+
import org.springframework.security.web.RedirectStrategy;
8+
import org.springframework.security.web.WebAttributes;
9+
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
10+
11+
import javax.servlet.http.HttpServletRequest;
12+
import javax.servlet.http.HttpServletResponse;
13+
import javax.servlet.http.HttpSession;
14+
import java.io.IOException;
15+
16+
import static com.okta.developer.jugtours.config.OAuth2Configuration.SAVED_LOGIN_ORIGIN_URI;
17+
18+
/**
19+
* AuthenticationSuccessHandler that looks for a saved login origin and redirects to it if it exists.
20+
*/
21+
public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
22+
23+
private final Logger log = LoggerFactory.getLogger(OAuth2AuthenticationSuccessHandler.class);
24+
25+
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
26+
27+
@Override
28+
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
29+
Authentication authentication)
30+
throws IOException {
31+
32+
handle(request, response);
33+
clearAuthenticationAttributes(request);
34+
}
35+
36+
private void handle(HttpServletRequest request, HttpServletResponse response)
37+
throws IOException {
38+
39+
String targetUrl = determineTargetUrl(request);
40+
41+
if (response.isCommitted()) {
42+
log.error("Response has already been committed. Unable to redirect to " + targetUrl);
43+
return;
44+
}
45+
46+
redirectStrategy.sendRedirect(request, response, targetUrl);
47+
}
48+
49+
private String determineTargetUrl(HttpServletRequest request) {
50+
Object savedReferrer = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI);
51+
if (savedReferrer != null) {
52+
String savedLoginOrigin = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI).toString();
53+
log.info("Redirecting to saved login origin URI: {}", savedLoginOrigin);
54+
request.getSession().removeAttribute(SAVED_LOGIN_ORIGIN_URI);
55+
return savedLoginOrigin;
56+
} else {
57+
return "/";
58+
}
59+
}
60+
61+
private void clearAuthenticationAttributes(HttpServletRequest request) {
62+
HttpSession session = request.getSession(false);
63+
if (session == null) {
64+
return;
65+
}
66+
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
67+
}
68+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package com.okta.developer.jugtours.config;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.beans.BeansException;
6+
import org.springframework.beans.factory.config.BeanPostProcessor;
7+
import org.springframework.boot.web.servlet.FilterRegistrationBean;
8+
import org.springframework.context.annotation.Bean;
9+
import org.springframework.context.annotation.Configuration;
10+
import org.springframework.context.annotation.Profile;
11+
import org.springframework.core.Ordered;
12+
import org.springframework.core.PriorityOrdered;
13+
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
14+
import org.springframework.security.web.FilterChainProxy;
15+
import org.springframework.security.web.SecurityFilterChain;
16+
import org.springframework.util.StringUtils;
17+
import org.springframework.web.filter.OncePerRequestFilter;
18+
19+
import javax.servlet.Filter;
20+
import javax.servlet.FilterChain;
21+
import javax.servlet.ServletException;
22+
import javax.servlet.http.HttpServletRequest;
23+
import javax.servlet.http.HttpServletResponse;
24+
import java.io.IOException;
25+
26+
/**
27+
* Development only configuration that is Browsersync-aware and redirects to the origin you clicked "login" from.
28+
* If you split your application into client and server into separate domains, you might want to enable this for prod
29+
* mode too.
30+
*/
31+
@Configuration
32+
@Profile("dev")
33+
public class OAuth2Configuration {
34+
public static final String SAVED_LOGIN_ORIGIN_URI = OAuth2Configuration.class.getName() + "_SAVED_ORIGIN";
35+
36+
private final Logger log = LoggerFactory.getLogger(OAuth2Configuration.class);
37+
38+
@Bean
39+
public FilterRegistrationBean<OncePerRequestFilter> saveLoginOriginFilter() {
40+
OncePerRequestFilter filter = new OncePerRequestFilter() {
41+
@Override
42+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
43+
FilterChain filterChain)
44+
throws ServletException, IOException {
45+
if (request.getRemoteUser() == null && request.getRequestURI().endsWith("/login")) {
46+
String referrer = request.getHeader("referer");
47+
if (!StringUtils.isEmpty(referrer) &&
48+
request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI) == null) {
49+
log.info("Saving login origin URI: {}", referrer);
50+
request.getSession().setAttribute(SAVED_LOGIN_ORIGIN_URI, referrer);
51+
}
52+
}
53+
filterChain.doFilter(request, response);
54+
}
55+
};
56+
FilterRegistrationBean<OncePerRequestFilter> bean = new FilterRegistrationBean<>(filter);
57+
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
58+
return bean;
59+
}
60+
61+
@Bean
62+
public static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
63+
return new DefaultRolesPrefixPostProcessor();
64+
}
65+
66+
public static class DefaultRolesPrefixPostProcessor implements BeanPostProcessor, PriorityOrdered {
67+
68+
@Override
69+
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
70+
if (bean instanceof FilterChainProxy) {
71+
72+
FilterChainProxy chains = (FilterChainProxy) bean;
73+
74+
for (SecurityFilterChain chain : chains.getFilterChains()) {
75+
for (Filter filter : chain.getFilters()) {
76+
if (filter instanceof OAuth2ClientAuthenticationProcessingFilter) {
77+
OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter =
78+
(OAuth2ClientAuthenticationProcessingFilter) filter;
79+
oAuth2ClientAuthenticationProcessingFilter
80+
.setAuthenticationSuccessHandler(new OAuth2AuthenticationSuccessHandler());
81+
}
82+
}
83+
}
84+
}
85+
return bean;
86+
}
87+
88+
@Override
89+
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
90+
return bean;
91+
}
92+
93+
@Override
94+
public int getOrder() {
95+
return PriorityOrdered.HIGHEST_PRECEDENCE;
96+
}
97+
}
98+
}
Lines changed: 1 addition & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -1,142 +1,23 @@
11
package com.okta.developer.jugtours.config;
22

3-
import org.slf4j.Logger;
4-
import org.slf4j.LoggerFactory;
53
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
6-
import org.springframework.context.annotation.Bean;
74
import org.springframework.context.annotation.Configuration;
8-
import org.springframework.context.annotation.Profile;
95
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10-
import org.springframework.security.config.annotation.web.builders.WebSecurity;
116
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12-
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
137
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
14-
import org.springframework.security.web.savedrequest.RequestCache;
15-
import org.springframework.security.web.savedrequest.SavedRequest;
16-
17-
import javax.servlet.http.Cookie;
18-
import javax.servlet.http.HttpServletRequest;
19-
import javax.servlet.http.HttpServletResponse;
20-
import javax.servlet.http.HttpSession;
21-
import java.util.Collection;
22-
import java.util.List;
23-
import java.util.Locale;
24-
import java.util.Map;
258

269
@Configuration
2710
@EnableOAuth2Sso
2811
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
29-
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
30-
31-
@Override
32-
public void configure(WebSecurity web) throws Exception {
33-
web.ignoring().antMatchers("/**/*.{js,html,css}");
34-
}
3512

3613
@Override
3714
protected void configure(HttpSecurity http) throws Exception {
38-
RequestCache requestCache = refererRequestCache();
39-
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
40-
handler.setRequestCache(requestCache);
4115
http
4216
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
43-
.and()
44-
.oauth2Login()
45-
.successHandler(handler)
4617
.and()
4718
.authorizeRequests()
4819
.antMatchers("/**/*.{js,html,css}").permitAll()
4920
.antMatchers("/", "/api/user").permitAll()
50-
.anyRequest().authenticated();/*
51-
.and()
52-
.requiresChannel()
53-
.requestMatchers(r -> r.getHeader("x-forwarded-proto") != null)
54-
.requiresSecure();*/
55-
}
56-
57-
@Bean
58-
@Profile("dev")
59-
public RequestCache refererRequestCache() {
60-
return new RequestCache() {
61-
private String savedAttrName = getClass().getName().concat(".SAVED");
62-
63-
@Override
64-
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
65-
String referrer = request.getHeader("referer");
66-
if (referrer != null) {
67-
request.getSession().setAttribute(this.savedAttrName, referrerRequest(referrer));
68-
}
69-
}
70-
71-
@Override
72-
public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) {
73-
HttpSession session = request.getSession(false);
74-
75-
if (session != null) {
76-
return (SavedRequest) session.getAttribute(this.savedAttrName);
77-
}
78-
79-
return null;
80-
}
81-
82-
@Override
83-
public HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response) {
84-
return request;
85-
}
86-
87-
@Override
88-
public void removeRequest(HttpServletRequest request, HttpServletResponse response) {
89-
HttpSession session = request.getSession(false);
90-
91-
if (session != null) {
92-
log.debug("Removing SavedRequest from session if present");
93-
session.removeAttribute(this.savedAttrName);
94-
}
95-
}
96-
};
97-
}
98-
99-
private SavedRequest referrerRequest(final String referrer) {
100-
return new SavedRequest() {
101-
@Override
102-
public String getRedirectUrl() {
103-
return referrer;
104-
}
105-
106-
@Override
107-
public List<Cookie> getCookies() {
108-
return null;
109-
}
110-
111-
@Override
112-
public String getMethod() {
113-
return null;
114-
}
115-
116-
@Override
117-
public List<String> getHeaderValues(String name) {
118-
return null;
119-
}
120-
121-
@Override
122-
public Collection<String> getHeaderNames() {
123-
return null;
124-
}
125-
126-
@Override
127-
public List<Locale> getLocales() {
128-
return null;
129-
}
130-
131-
@Override
132-
public String[] getParameterValues(String name) {
133-
return new String[0];
134-
}
135-
136-
@Override
137-
public Map<String, String[]> getParameterMap() {
138-
return null;
139-
}
140-
};
21+
.anyRequest().authenticated();
14122
}
14223
}

src/main/java/com/okta/developer/jugtours/model/Group.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public class Group {
2525
private String stateOrProvince;
2626
private String country;
2727
private String postalCode;
28-
@ManyToOne
28+
@ManyToOne(cascade=CascadeType.ALL)
2929
private User user;
3030

3131
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)

src/main/java/com/okta/developer/jugtours/model/GroupEventHandler.java

Lines changed: 0 additions & 26 deletions
This file was deleted.

src/main/java/com/okta/developer/jugtours/web/GroupController.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,21 @@
22

33
import com.okta.developer.jugtours.model.Group;
44
import com.okta.developer.jugtours.model.GroupRepository;
5+
import com.okta.developer.jugtours.model.User;
56
import org.slf4j.Logger;
67
import org.slf4j.LoggerFactory;
78
import org.springframework.http.HttpStatus;
89
import org.springframework.http.ResponseEntity;
10+
import org.springframework.security.core.context.SecurityContextHolder;
11+
import org.springframework.security.oauth2.provider.OAuth2Authentication;
912
import org.springframework.web.bind.annotation.*;
1013

1114
import javax.validation.Valid;
1215
import java.net.URI;
1316
import java.net.URISyntaxException;
1417
import java.security.Principal;
1518
import java.util.Collection;
19+
import java.util.Map;
1620
import java.util.Optional;
1721

1822
@RestController
@@ -39,8 +43,13 @@ ResponseEntity<?> getGroup(@PathVariable Long id) {
3943
}
4044

4145
@PostMapping("/group")
42-
ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
46+
ResponseEntity<Group> createGroup(@Valid @RequestBody Group group, Principal principal) throws URISyntaxException {
4347
log.info("Request to create group: {}", group);
48+
OAuth2Authentication authentication = (OAuth2Authentication) principal;
49+
Map<String, Object> details = (Map<String, Object>) authentication.getUserAuthentication().getDetails();
50+
User user = new User(details.get("sub").toString(),
51+
details.get("name").toString(), details.get("email").toString());
52+
group.setUser(user);
4453
Group result = repository.save(group);
4554
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
4655
.body(result);

0 commit comments

Comments
 (0)