Skip to content

Commit f921036

Browse files
committed
Handling accessDenied
1 parent e4e8042 commit f921036

5 files changed

Lines changed: 92 additions & 7 deletions

File tree

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,58 @@
11
package org.baeldung.spring;
22

3+
import org.baeldung.web.error.CustomAccessDeniedHandler;
4+
import org.springframework.beans.factory.annotation.Autowired;
35
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
46
import org.springframework.context.annotation.Configuration;
5-
import org.springframework.context.annotation.ImportResource;
7+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
9+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
11+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
12+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
613

714
@Configuration
815
@EnableAutoConfiguration
9-
@ImportResource({ "classpath:webSecurityConfig.xml" })
10-
public class SecSecurityConfig {
16+
//
17+
@EnableWebSecurity
18+
@EnableGlobalMethodSecurity(prePostEnabled = true)
19+
// @ImportResource({ "classpath:webSecurityConfig.xml" })
20+
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
21+
22+
@Autowired
23+
private CustomAccessDeniedHandler accessDeniedHandler;
1124

1225
public SecSecurityConfig() {
1326
super();
1427
}
1528

29+
// java config
30+
31+
@Override
32+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
33+
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
34+
}
35+
36+
@Override
37+
public void configure(final WebSecurity web) throws Exception {
38+
web.ignoring().antMatchers("/resources/**");
39+
}
40+
41+
@Override
42+
protected void configure(final HttpSecurity http) throws Exception {
43+
// @formatter:off
44+
http
45+
.csrf().disable()
46+
.authorizeRequests()
47+
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
48+
.anyRequest().authenticated()
49+
.and()
50+
.httpBasic()
51+
.and()
52+
// .exceptionHandling().accessDeniedPage("/my-error-page")
53+
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
54+
;
55+
// @formatter:on
56+
}
57+
1658
}

‎spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import org.baeldung.web.util.LinkUtil;
1212
import org.springframework.beans.factory.annotation.Autowired;
1313
import org.springframework.http.HttpStatus;
14+
import org.springframework.security.access.prepost.PreAuthorize;
1415
import org.springframework.stereotype.Controller;
1516
import org.springframework.web.bind.annotation.RequestMapping;
1617
import org.springframework.web.bind.annotation.RequestMethod;
@@ -51,6 +52,7 @@ public Map getMetric() {
5152
return metricService.getFullMetric();
5253
}
5354

55+
@PreAuthorize("hasRole('ROLE_ADMIN')")
5456
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
5557
@ResponseBody
5658
public Map getStatusMetric() {
@@ -67,9 +69,16 @@ public Object[][] drawMetric() {
6769
return result;
6870
}
6971

70-
@RequestMapping(value = "/metric-graph-data", method = RequestMethod.GET)
72+
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
7173
@ResponseBody
72-
public Object[][] getActuatorMetricData() {
73-
return actMetricService.getGraphData();
74+
public String sampleAdminPage() {
75+
return "Hello";
7476
}
77+
78+
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
79+
@ResponseBody
80+
public String sampleErrorPage() {
81+
return "Error Occurred";
82+
}
83+
7584
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.web.error;
2+
3+
import java.io.IOException;
4+
5+
import javax.servlet.ServletException;
6+
import javax.servlet.http.HttpServletRequest;
7+
import javax.servlet.http.HttpServletResponse;
8+
9+
import org.springframework.security.access.AccessDeniedException;
10+
import org.springframework.security.web.access.AccessDeniedHandler;
11+
import org.springframework.stereotype.Component;
12+
13+
@Component
14+
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
15+
16+
@Override
17+
public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException ex) throws IOException, ServletException {
18+
response.getOutputStream().print("Error Message Goes Here");
19+
// response.sendRedirect("/my-error-page");
20+
}
21+
22+
}

‎spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@
1111
import org.springframework.http.HttpStatus;
1212
import org.springframework.http.ResponseEntity;
1313
import org.springframework.http.converter.HttpMessageNotReadableException;
14+
import org.springframework.security.access.AccessDeniedException;
1415
import org.springframework.web.bind.MethodArgumentNotValidException;
1516
import org.springframework.web.bind.annotation.ControllerAdvice;
1617
import org.springframework.web.bind.annotation.ExceptionHandler;
1718
import org.springframework.web.context.request.WebRequest;
1819
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
20+
//import org.springframework.security.access.AccessDeniedException;
1921

2022
@ControllerAdvice
2123
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@@ -54,6 +56,11 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgume
5456
}
5557

5658
// 403
59+
@ExceptionHandler({ AccessDeniedException.class })
60+
public ResponseEntity<Object> handleAccessDeniedException(final Exception ex, final WebRequest request) {
61+
System.out.println("request" + request.getUserPrincipal());
62+
return new ResponseEntity<Object>("Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
63+
}
5764

5865
// 404
5966

‎spring-security-rest-full/src/main/resources/webSecurityConfig.xml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,24 @@
99

1010
<http pattern="/securityNone" security="none"/>
1111

12-
<http use-expressions="true">
12+
<http use-expressions="true" >
13+
<intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>
1314
<intercept-url pattern="/**" access="isAuthenticated()"/>
1415

1516
<http-basic/>
1617

1718
<csrf disabled="true"/>
1819

20+
<!-- <access-denied-handler error-page="/my-error-page" /> -->
21+
22+
<access-denied-handler ref="customAccessDeniedHandler" />
1923
</http>
2024

2125
<authentication-manager>
2226
<authentication-provider>
2327
<user-service>
2428
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
29+
<user name="admin" password="adminPass" authorities="ROLE_ADMIN"/>
2530
</user-service>
2631
</authentication-provider>
2732
</authentication-manager>

0 commit comments

Comments
 (0)