Handling accessDenied

This commit is contained in:
DOHA 2015-12-31 13:02:15 +02:00 committed by David Morley
parent d9a91f0d28
commit 7a35c66a62
5 changed files with 92 additions and 7 deletions

View File

@ -1,16 +1,58 @@
package org.baeldung.spring;
import org.baeldung.web.error.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableAutoConfiguration
@ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
//
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
// @ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
public SecSecurityConfig() {
super();
}
// java config
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
}
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
// .exceptionHandling().accessDeniedPage("/my-error-page")
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
;
// @formatter:on
}
}

View File

@ -11,6 +11,7 @@ import org.baeldung.web.metric.IMetricService;
import org.baeldung.web.util.LinkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@ -51,6 +52,7 @@ public class RootController {
return metricService.getFullMetric();
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
@ResponseBody
public Map getStatusMetric() {
@ -67,9 +69,16 @@ public class RootController {
return result;
}
@RequestMapping(value = "/metric-graph-data", method = RequestMethod.GET)
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
@ResponseBody
public Object[][] getActuatorMetricData() {
return actMetricService.getGraphData();
public String sampleAdminPage() {
return "Hello";
}
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
@ResponseBody
public String sampleErrorPage() {
return "Error Occurred";
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.web.error;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException ex) throws IOException, ServletException {
response.getOutputStream().print("Error Message Goes Here");
// response.sendRedirect("/my-error-page");
}
}

View File

@ -11,11 +11,13 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
//import org.springframework.security.access.AccessDeniedException;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ -54,6 +56,11 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH
}
// 403
@ExceptionHandler({ AccessDeniedException.class })
public ResponseEntity<Object> handleAccessDeniedException(final Exception ex, final WebRequest request) {
System.out.println("request" + request.getUserPrincipal());
return new ResponseEntity<Object>("Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
}
// 404

View File

@ -9,19 +9,24 @@
<http pattern="/securityNone" security="none"/>
<http use-expressions="true">
<http use-expressions="true" >
<intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<http-basic/>
<csrf disabled="true"/>
<!-- <access-denied-handler error-page="/my-error-page" /> -->
<access-denied-handler ref="customAccessDeniedHandler" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
<user name="admin" password="adminPass" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>