-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathSpringBoot2App.java
319 lines (258 loc) · 11.7 KB
/
SpringBoot2App.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package demo;
import static org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoderJwkSupport;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@SpringBootApplication
public class SpringBoot2App {
public static void main(String[] args) {
SpringApplication.run(SpringBoot2App.class, args);
}
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfig {
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurer( //
KeycloakOauth2UserService keycloakOidcUserService, //
KeycloakLogoutHandler keycloakLogoutHandler //
) {
return new WebSecurityConfigurerAdapter() {
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Configure session management to your needs.
// I need this as a basis for a classic, server side rendered application
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and()
// Depends on your taste. You can configure single paths here
// or allow everything a I did and then use method based security
// like in the controller below
.authorizeRequests().anyRequest().permitAll().and()
// Propagate logouts via /logout to Keycloak
.logout().addLogoutHandler(keycloakLogoutHandler).and()
// This is the point where OAuth2 login of Spring 5 gets enabled
.oauth2Login().userInfoEndpoint().oidcUserService(keycloakOidcUserService).and()
// I don't want a page with different clients as login options
// So i use the constant from OAuth2AuthorizationRequestRedirectFilter
// plus the configured realm as immediate redirect to Keycloak
// .loginPage(DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + realm);
.loginPage("/login-redirector");
}
};
}
@Bean
Object foo(ClientRegistrationRepository clientRegistrationRepository) {
return new OAuth2AuthorizationRequestRedirectFilter(clientRegistrationRepository);
}
@Bean
KeycloakOauth2UserService keycloakOidcUserService(OAuth2ClientProperties oauth2ClientProperties) {
// TODO use default JwtDecoder - where to grab?
JwtDecoder jwtDecoder = new TenantAwareDynamicJwtDecoder(oauth2ClientProperties);
SimpleAuthorityMapper authoritiesMapper = new SimpleAuthorityMapper();
authoritiesMapper.setConvertToUpperCase(true);
return new KeycloakOauth2UserService(jwtDecoder, authoritiesMapper);
}
@Bean
KeycloakLogoutHandler keycloakLogoutHandler() {
return new KeycloakLogoutHandler(new RestTemplate());
}
}
class TenantAwareDynamicJwtDecoder implements JwtDecoder {
private final NimbusJwtDecoderJwkSupport defaultJwtDecoder;
private final NimbusJwtDecoderJwkSupport demo2JwtDecoder;
public TenantAwareDynamicJwtDecoder(OAuth2ClientProperties oauth2ClientProperties) {
// TODO hard coded tenant aware jwt decoders for now... replace with lazily
// computed cache
this.defaultJwtDecoder = new NimbusJwtDecoderJwkSupport(
oauth2ClientProperties.getProvider().get("keycloak").getJwkSetUri());
this.demo2JwtDecoder = new NimbusJwtDecoderJwkSupport(
oauth2ClientProperties.getProvider().get("keycloak-demo2").getJwkSetUri());
}
@Override
public Jwt decode(String token) throws JwtException {
return selectDecoder().decode(token);
}
private JwtDecoder selectDecoder() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
if (request.getServerName().startsWith("demo2.")) {
return demo2JwtDecoder;
}
return defaultJwtDecoder;
}
}
@RequiredArgsConstructor
class KeycloakOauth2UserService extends OidcUserService {
private final OAuth2Error INVALID_REQUEST = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
private final JwtDecoder jwtDecoder;
private final GrantedAuthoritiesMapper authoritiesMapper;
/**
* Augments {@link OidcUserService#loadUser(OidcUserRequest)} to add authorities
* provided by Keycloak.
*
* Needed because {@link OidcUserService#loadUser(OidcUserRequest)} (currently)
* does not provide a hook for adding custom authorities from a
* {@link OidcUserRequest}.
*/
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser user = super.loadUser(userRequest);
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.addAll(user.getAuthorities());
authorities.addAll(extractKeycloakAuthorities(userRequest));
return new DefaultOidcUser(authorities, userRequest.getIdToken(), user.getUserInfo(), "preferred_username");
}
/**
* Extracts {@link GrantedAuthority GrantedAuthorities} from the AccessToken in
* the {@link OidcUserRequest}.
*
* @param userRequest
* @return
*/
private Collection<? extends GrantedAuthority> extractKeycloakAuthorities(OidcUserRequest userRequest) {
Jwt token = null;
try {
// Token is already verified by spring security infrastructure
token = jwtDecoder.decode(userRequest.getAccessToken().getTokenValue());
} catch (JwtException e) {
throw new OAuth2AuthenticationException(INVALID_REQUEST, e);
}
// Would be great if Spring Security would provide something like a plugable
// OidcUserRequestAuthoritiesExtractor interface to hide the junk below...
@SuppressWarnings("unchecked")
Map<String, Object> resourceMap = (Map<String, Object>) token.getClaims().get("resource_access");
String clientId = userRequest.getClientRegistration().getClientId();
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> clientResource = (Map<String, Map<String, Object>>) resourceMap.get(clientId);
if (CollectionUtils.isEmpty(clientResource)) {
return Collections.emptyList();
}
@SuppressWarnings("unchecked")
List<String> clientRoles = (List<String>) clientResource.get("roles");
if (CollectionUtils.isEmpty(clientRoles)) {
return Collections.emptyList();
}
Collection<? extends GrantedAuthority> authorities = AuthorityUtils
.createAuthorityList(clientRoles.toArray(new String[0]));
if (authoritiesMapper != null) {
authorities = authoritiesMapper.mapAuthorities(authorities);
}
return authorities;
}
}
/**
* Propagates logouts to Keycloak.
*
* Necessary because Spring Security 5 (currently) doesn't support
* end-session-endpoints.
*/
@Slf4j
@RequiredArgsConstructor
class KeycloakLogoutHandler extends SecurityContextLogoutHandler {
private final RestTemplate restTemplate;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
super.logout(request, response, authentication);
propagateLogoutToKeycloak((OidcUser) authentication.getPrincipal());
}
private void propagateLogoutToKeycloak(OidcUser user) {
String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(endSessionEndpoint) //
.queryParam("id_token_hint", user.getIdToken().getTokenValue());
ResponseEntity<String> logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class);
if (logoutResponse.getStatusCode().is2xxSuccessful()) {
log.info("Successfulley logged out in Keycloak");
} else {
log.info("Could not propagate logout to Keycloak");
}
}
}
@Controller
class DemoController {
@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/protected")
public ModelAndView protectedPage(Principal principal) {
return new ModelAndView("app", Collections.singletonMap("principal", principal));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin")
public ModelAndView adminPage(Principal principal) {
return new ModelAndView("admin", Collections.singletonMap("principal", principal));
}
@GetMapping("/")
public String unprotectedPage(Model model, Principal principal) {
model.addAttribute("principal", principal);
return "index";
}
@GetMapping("/account")
public String redirectToAccountPage(@AuthenticationPrincipal OAuth2AuthenticationToken authToken) {
if (authToken == null) {
return "redirect:/";
}
OidcUser user = (OidcUser) authToken.getPrincipal();
// Provides a back-link to the application
return "redirect:" + user.getIssuer() + "/account?referrer=" + user.getIdToken().getAuthorizedParty();
}
/**
* Determines the login route to use based on the Host header.
* @param request
* @return
*/
@GetMapping("/login-redirector")
public String loginRedirect(HttpServletRequest request) {
//TODO use proper subdomain extraction
if (request.getServerName().startsWith("demo2.")) {
return "redirect:" + DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/demo2";
}
return "redirect:" + DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/demo";
}
}