Expression-Based Access Control (#517)
* Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions
This commit is contained in:
parent
34414b2a43
commit
042878628f
|
@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
|
||||||
http
|
http
|
||||||
.csrf().disable()
|
.csrf().disable()
|
||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
|
.antMatchers("/auth/admin/*").hasRole("ADMIN")
|
||||||
.anyRequest().authenticated()
|
.antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
|
||||||
|
.antMatchers("/*").permitAll()
|
||||||
.and()
|
.and()
|
||||||
.httpBasic()
|
.httpBasic()
|
||||||
.and()
|
.and()
|
||||||
|
|
|
@ -14,24 +14,25 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
public WebConfig() {
|
public WebConfig() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver viewResolver() {
|
public ViewResolver viewResolver() {
|
||||||
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||||
viewResolver.setPrefix("/WEB-INF/view/");
|
viewResolver.setPrefix("/WEB-INF/view/");
|
||||||
viewResolver.setSuffix(".jsp");
|
viewResolver.setSuffix(".jsp");
|
||||||
return viewResolver;
|
return viewResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||||
super.addViewControllers(registry);
|
super.addViewControllers(registry);
|
||||||
registry.addViewController("/graph.html");
|
registry.addViewController("/graph.html");
|
||||||
registry.addViewController("/csrfHome.html");
|
registry.addViewController("/csrfHome.html");
|
||||||
}
|
registry.addViewController("/homepage.html");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -12,21 +12,22 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
|
||||||
// to test csrf
|
// to test csrf
|
||||||
@Controller
|
@Controller
|
||||||
|
@RequestMapping(value = "/auth/")
|
||||||
public class BankController {
|
public class BankController {
|
||||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||||
logger.info("Transfer to {}", accountNo);
|
logger.info("Transfer to {}", accountNo);
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
// write - just for test
|
// write - just for test
|
||||||
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||||
logger.info("Transfer to {}", accountNo);
|
logger.info("Transfer to {}", accountNo);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,93 +29,93 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||||
import com.google.common.base.Preconditions;
|
import com.google.common.base.Preconditions;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
@RequestMapping(value = "/foos")
|
@RequestMapping(value = "/auth/foos")
|
||||||
public class FooController {
|
public class FooController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ApplicationEventPublisher eventPublisher;
|
private ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IFooService service;
|
private IFooService service;
|
||||||
|
|
||||||
public FooController() {
|
public FooController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
@ResponseStatus(value = HttpStatus.OK)
|
@ResponseStatus(value = HttpStatus.OK)
|
||||||
public long count() {
|
public long count() {
|
||||||
return 2l;
|
return 2l;
|
||||||
}
|
}
|
||||||
|
|
||||||
// read - one
|
// read - one
|
||||||
|
|
||||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
||||||
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
||||||
|
|
||||||
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
||||||
return resourceById;
|
return resourceById;
|
||||||
}
|
}
|
||||||
|
|
||||||
// read - all
|
// read - all
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET)
|
@RequestMapping(method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<Foo> findAll() {
|
public List<Foo> findAll() {
|
||||||
return service.findAll();
|
return service.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
||||||
final Page<Foo> resultPage = service.findPaginated(page, size);
|
final Page<Foo> resultPage = service.findPaginated(page, size);
|
||||||
if (page > resultPage.getTotalPages()) {
|
if (page > resultPage.getTotalPages()) {
|
||||||
throw new MyResourceNotFoundException();
|
throw new MyResourceNotFoundException();
|
||||||
}
|
}
|
||||||
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
||||||
|
|
||||||
return resultPage.getContent();
|
return resultPage.getContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
// write
|
// write
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST)
|
@RequestMapping(method = RequestMethod.POST)
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
final Foo foo = service.create(resource);
|
final Foo foo = service.create(resource);
|
||||||
final Long idOfCreatedResource = foo.getId();
|
final Long idOfCreatedResource = foo.getId();
|
||||||
|
|
||||||
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
|
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
|
||||||
|
|
||||||
return foo;
|
return foo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
||||||
service.update(resource);
|
service.update(resource);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void delete(@PathVariable("id") final Long id) {
|
public void delete(@PathVariable("id") final Long id) {
|
||||||
service.deleteById(id);
|
service.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.HEAD)
|
@RequestMapping(method = RequestMethod.HEAD)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void head(final HttpServletResponse resp) {
|
public void head(final HttpServletResponse resp) {
|
||||||
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
resp.setHeader("bar", "baz");
|
resp.setHeader("bar", "baz");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,14 @@
|
||||||
|
package org.baeldung.web.controller;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping(value = "/")
|
||||||
|
public class HomeController {
|
||||||
|
|
||||||
|
public String index() {
|
||||||
|
return "homepage";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -20,65 +20,66 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
import org.springframework.web.util.UriTemplate;
|
import org.springframework.web.util.UriTemplate;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
|
@RequestMapping(value = "/auth/")
|
||||||
public class RootController {
|
public class RootController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IMetricService metricService;
|
private IMetricService metricService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IActuatorMetricService actMetricService;
|
private IActuatorMetricService actMetricService;
|
||||||
|
|
||||||
public RootController() {
|
public RootController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
// discover
|
// discover
|
||||||
|
|
||||||
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
||||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||||
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
||||||
final String rootUri = request.getRequestURL().toString();
|
final String rootUri = request.getRequestURL().toString();
|
||||||
|
|
||||||
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
||||||
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
||||||
response.addHeader("Link", linkToFoo);
|
response.addHeader("Link", linkToFoo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Map getMetric() {
|
public Map getMetric() {
|
||||||
return metricService.getFullMetric();
|
return metricService.getFullMetric();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||||
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Map getStatusMetric() {
|
public Map getStatusMetric() {
|
||||||
return metricService.getStatusMetric();
|
return metricService.getStatusMetric();
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Object[][] drawMetric() {
|
public Object[][] drawMetric() {
|
||||||
final Object[][] result = metricService.getGraphData();
|
final Object[][] result = metricService.getGraphData();
|
||||||
for (int i = 1; i < result[0].length; i++) {
|
for (int i = 1; i < result[0].length; i++) {
|
||||||
result[0][i] = result[0][i].toString();
|
result[0][i] = result[0][i].toString();
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String sampleAdminPage() {
|
public String sampleAdminPage() {
|
||||||
return "Hello";
|
return "Hello";
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String sampleErrorPage() {
|
public String sampleErrorPage() {
|
||||||
return "Error Occurred";
|
return "Error Occurred";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,96 +37,97 @@ import cz.jirutka.rsql.parser.ast.Node;
|
||||||
|
|
||||||
//@EnableSpringDataWebSupport
|
//@EnableSpringDataWebSupport
|
||||||
@Controller
|
@Controller
|
||||||
|
@RequestMapping(value = "/auth/")
|
||||||
public class UserController {
|
public class UserController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IUserDAO service;
|
private IUserDAO service;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository dao;
|
private UserRepository dao;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MyUserRepository myUserRepository;
|
private MyUserRepository myUserRepository;
|
||||||
|
|
||||||
public UserController() {
|
public UserController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API - READ
|
// API - READ
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
||||||
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
||||||
if (search != null) {
|
if (search != null) {
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return service.searchUser(params);
|
return service.searchUser(params);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
||||||
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
||||||
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
final Specification<User> spec = builder.build();
|
final Specification<User> spec = builder.build();
|
||||||
return dao.findAll(spec);
|
return dao.findAll(spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
||||||
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
||||||
if (search != null) {
|
if (search != null) {
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
final BooleanExpression exp = builder.build();
|
final BooleanExpression exp = builder.build();
|
||||||
return myUserRepository.findAll(exp);
|
return myUserRepository.findAll(exp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
||||||
final Node rootNode = new RSQLParser().parse(search);
|
final Node rootNode = new RSQLParser().parse(search);
|
||||||
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
||||||
return dao.findAll(spec);
|
return dao.findAll(spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
||||||
return myUserRepository.findAll(predicate);
|
return myUserRepository.findAll(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
// API - WRITE
|
// API - WRITE
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public void create(@RequestBody final User resource) {
|
public void create(@RequestBody final User resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
dao.save(resource);
|
dao.save(resource);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public void addMyUser(@RequestBody final MyUser resource) {
|
public void addMyUser(@RequestBody final MyUser resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
myUserRepository.save(resource);
|
myUserRepository.save(resource);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,26 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
public class CsrfAbstractIntegrationTest {
|
public class CsrfAbstractIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WebApplicationContext context;
|
private WebApplicationContext context;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Filter springSecurityFilterChain;
|
private Filter springSecurityFilterChain;
|
||||||
|
|
||||||
protected MockMvc mvc;
|
protected MockMvc mvc;
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected RequestPostProcessor testUser() {
|
protected RequestPostProcessor testUser() {
|
||||||
return user("user").password("userPass").roles("USER");
|
return user("user").password("userPass").roles("USER");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String createFoo() throws JsonProcessingException {
|
protected RequestPostProcessor testAdmin() {
|
||||||
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
return user("admin").password("adminPass").roles("USER", "ADMIN");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected String createFoo() throws JsonProcessingException {
|
||||||
|
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
package org.baeldung.security.csrf;
|
package org.baeldung.security.csrf;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@ -13,14 +14,33 @@ import org.springframework.test.context.ContextConfiguration;
|
||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
||||||
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
||||||
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void accessMainPageWithoutAuthorization() throws Exception {
|
||||||
|
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void accessOtherPages() throws Exception {
|
||||||
|
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
|
||||||
|
.andExpect(status().isUnauthorized()); // without authorization
|
||||||
|
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser()))
|
||||||
|
.andExpect(status().isOk()); // with authorization
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void accessAdminPage() throws Exception {
|
||||||
|
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization
|
||||||
|
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue