move security content from spring-security-rest-full (#2731)
* move security content from spring-security-rest-full * swagger update
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
e7252f61aa
commit
3ed7609758
@@ -1,10 +1,13 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler;
|
||||
import org.baeldung.web.error.CustomAccessDeniedHandler;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
@@ -13,9 +16,13 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
@ComponentScan("org.baeldung.security")
|
||||
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private CustomAccessDeniedHandler accessDeniedHandler;
|
||||
|
||||
// @Autowired
|
||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
|
||||
@@ -40,14 +47,15 @@ public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.and()
|
||||
.exceptionHandling()
|
||||
// .authenticationEntryPoint(restAuthenticationEntryPoint)
|
||||
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
|
||||
// .authenticationEntryPoint(restAuthenticationEntryPoint)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/api/csrfAttacker*").permitAll()
|
||||
.antMatchers("/api/customer/**").permitAll()
|
||||
.antMatchers("/api/foos/**").authenticated()
|
||||
.antMatchers("/api/async/**").permitAll()
|
||||
.antMatchers("/api/admin/**").hasRole("ADMIN")
|
||||
.and()
|
||||
.httpBasic()
|
||||
// .and()
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import static com.google.common.collect.Lists.newArrayList;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.builders.ResponseMessageBuilder;
|
||||
import springfox.documentation.schema.ModelRef;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
import static com.google.common.collect.Lists.newArrayList;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
public class SwaggerConfig {
|
||||
@@ -25,7 +29,7 @@ public class SwaggerConfig {
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "myeaddress@company.com", "License of API", "API license URL");
|
||||
ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", new Contact("John Doe", "www.example.com", "myeaddress@company.com"), "License of API", "API license URL", Collections.emptyList());
|
||||
return apiInfo;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class RootController {
|
||||
|
||||
public RootController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleAdminPage() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleErrorPage() {
|
||||
return "Error Occurred";
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
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.setStatus(403);
|
||||
// response.sendRedirect("/my-error-page");
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package org.baeldung.web.error;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
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 {
|
||||
|
||||
public RestResponseEntityExceptionHandler() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// 400
|
||||
|
||||
@ExceptionHandler({ DataIntegrityViolationException.class })
|
||||
public ResponseEntity<Object> handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) {
|
||||
final String bodyOfResponse = "This should be application specific";
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
|
||||
final String bodyOfResponse = "This should be application specific";
|
||||
// ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on
|
||||
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
|
||||
final String bodyOfResponse = "This should be application specific";
|
||||
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 409
|
||||
|
||||
@ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class })
|
||||
protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request) {
|
||||
final String bodyOfResponse = "This should be application specific";
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
|
||||
}
|
||||
|
||||
// 412
|
||||
|
||||
// 500
|
||||
|
||||
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class })
|
||||
/*500*/public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
|
||||
logger.error("500 Status Code", ex);
|
||||
final String bodyOfResponse = "This should be application specific";
|
||||
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package org.baeldung.web.exception;
|
||||
|
||||
public final class MyResourceNotFoundException extends RuntimeException {
|
||||
|
||||
public MyResourceNotFoundException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyResourceNotFoundException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public MyResourceNotFoundException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public MyResourceNotFoundException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
|
||||
|
||||
<http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
|
||||
<intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>
|
||||
|
||||
<intercept-url pattern="/api/**" access="isAuthenticated()" />
|
||||
|
||||
<csrf disabled="true" />
|
||||
@@ -17,6 +19,11 @@
|
||||
<form-login authentication-success-handler-ref="mySuccessHandler"
|
||||
authentication-failure-handler-ref="myFailureHandler" />
|
||||
|
||||
|
||||
<!-- <access-denied-handler error-page="/my-error-page" /> -->
|
||||
|
||||
<access-denied-handler ref="customAccessDeniedHandler" />
|
||||
|
||||
<logout />
|
||||
</http>
|
||||
|
||||
@@ -30,8 +37,12 @@
|
||||
<user-service>
|
||||
<user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
|
||||
<user name="user" password="userPass" authorities="ROLE_USER" />
|
||||
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
|
||||
<user name="admin" password="adminPass" authorities="ROLE_ADMIN"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
|
||||
<global-method-security pre-post-annotations="enabled"/>
|
||||
|
||||
</beans:beans>
|
||||
Reference in New Issue
Block a user