KeycloakSecurityContext is returning null in SpringBoot - java

I am creating an SPA with Keycloak 5, Spring Boot 2 and Angular 7.
Everything was fine, even keycloack configuration in application.properties and roles securing. But when I tried to create a Bean to get the User Token Data, I am receiving a null bean of it. Can't understand why, it is just like the code in Keycloak documentation...
import javax.servlet.http.HttpServletRequest;
import org.keycloak.KeycloakSecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
#Configuration
public class KeycloakConfig {
/**
* Retorna o contexto de segurança do Keycloak.
*
* #return
*/
#Bean
#Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public KeycloakSecurityContext accessToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
}
}
Boot Config:
keycloak.enabled = true
keycloak.auth-server-url = http://acesso.tre-pa.jus.br/auth
keycloak.realm = TRE-PA
keycloak.resource = acesso-sistemas-service
keycloak.credentials.secret = ca70294a-af51-4abb-81f9-234566de2c7c
keycloak.ssl-required = external
keycloak.use-resource-role-mappings = false
keycloak.bearer-only = true
keycloak.autodetect-bearer-only = true
keycloak.principal-attribute = preferred_username
logging.level.org.keycloak = DEBUG
spring.main.allow-bean-definition-overriding = true
# spring.autoconfigure.exclude = org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration
keycloak.securityConstraints[0].securityCollections[0].name = secured-area
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /secured/*
keycloak.securityConstraints[1].securityCollections[0].patterns[1] = /admin/*
keycloak.securityConstraints[1].authRoles[0] = DEVELOPER
keycloak.securityConstraints[1].securityCollections[0].name = service-area
keycloak.securityConstraints[1].securityCollections[0].patterns[0] = /service/*

I did something similar in my application using Keycloak 4.8.1.Final where I could access the AccessToken and expose it as a bean for injection into other classes:
#Bean
#Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken getAccessToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
KeycloakPrincipal<RefreshableKeycloakSecurityContext> keycloakPrincipal = (KeycloakPrincipal) request.getUserPrincipal();
if (keycloakPrincipal == null) {
throw new NotAuthenticatedException("KeycloakPrincipal not set");
}
KeycloakSecurityContext keycloakSecurityContext = keycloakPrincipal.getKeycloakSecurityContext();
return keycloakSecurityContext.getToken();
}
After upgrading Keycloak to 5 (and above all the way to 15.0.1) the code above no longer works. The only way I managed to get a reference to the AccessToken was by using Spring Security as described (mostly) here
Basically adding spring security deps to gradle
implementation('org.springframework.boot:spring-boot-starter-security')
Adding this config class...
import org.keycloak.adapters.KeycloakConfigResolver
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter
import org.springframework.context.annotation.Bean
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.core.authority.mapping.SimpleAuthorityMapper
import org.springframework.security.core.session.SessionRegistryImpl
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
import javax.inject.Inject
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(jsr250Enabled = true)
class KeycloakConfig : KeycloakWebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
super.configure(http)
http.authorizeRequests()
.anyRequest()
.permitAll()
http.csrf().disable()
}
#Inject
fun configureGlobal(authManager: AuthenticationManagerBuilder) {
val authProvider = keycloakAuthenticationProvider()
authProvider.setGrantedAuthoritiesMapper(SimpleAuthorityMapper())
authManager.authenticationProvider(authProvider)
}
#Bean
override fun sessionAuthenticationStrategy(): SessionAuthenticationStrategy {
return RegisterSessionAuthenticationStrategy(SessionRegistryImpl())
}
}
And then updating my method in my other config class:
import org.springframework.amqp.rabbit.annotation.EnableRabbit
import org.springframework.cache.annotation.EnableCaching
import org.springframework.context.annotation.EnableAspectJAutoProxy
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.web.context.WebApplicationContext
import org.springframework.context.annotation.ScopedProxyMode
import org.keycloak.representations.AccessToken
import javax.servlet.http.HttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import org.keycloak.KeycloakPrincipal
import org.keycloak.adapters.RefreshableKeycloakSecurityContext
import org.keycloak.KeycloakSecurityContext
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import javax.inject.Inject
import javax.ws.rs.NotAuthorizedException
import javax.ws.rs.core.Context
import javax.ws.rs.core.SecurityContext
#Configuration
class ApplicationConfig {
//needed for keycloak adaptor 7.0.1+
// added in this here rather than in KeycloakConfig above due to issue here:
// https://stackoverflow.com/questions/57957006/unable-to-build-spring-based-project-for-authentication-using-keycloak
#Bean
fun keycloakConfigResolver(): KeycloakSpringBootConfigResolver {
return KeycloakSpringBootConfigResolver()
}
#Bean
#Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
fun accessToken(): AccessToken {
val request = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes).request
val token = request.userPrincipal as KeycloakAuthenticationToken? ?: throw NotAuthorizedException("KeycloakPrincipal not set")
val principal = token.principal as KeycloakPrincipal<*>
val keycloakSecurityContext = principal.keycloakSecurityContext
return keycloakSecurityContext.token
}
}
The above codes works for me with Springboot versions 2.1.2.RELEASE and 2.5.3

Related

Configuration in Resilience4J CircuitBreaker not working

I'm using a circuit breaker of Resilience4J and I need to ignore some custom exceptions so I need to change the default configuration. I'm working with microservices so I have a microservice connected to a database which have some basic requests like get by id and I also have an edge service which use these requests. I need, for example, if the id doesn't exist, the microservice throws a custom exception and the circuitbreaker doesn't open in this case.
Microservice with the database:
Get request
#GetMapping("/sales-rep/{id}")
#ResponseStatus(HttpStatus.OK)
public SalesRepDTO getSalesRep(#PathVariable Integer id) {
return salesRepService.getSalesRep(id);
}
Service
public SalesRepDTO getSalesRep(Integer id) {
if(salesRepRepository.existsById(id)) {
SalesRep salesRep = salesRepRepository.findById(id).get();
return new SalesRepDTO(salesRep.getId(), salesRep.getName());
} else {
throw new SalesRepNotFoundException("Sales rep not found");
}
}
Edge service:
Service
import com.ironhack.manageAllservice.client.AccountClient;
import com.ironhack.manageAllservice.client.LeadClient;
import com.ironhack.manageAllservice.client.SalesRepClient;
import com.ironhack.manageAllservice.controller.dtos.*;
import com.ironhack.manageAllservice.controller.dtos.report.OpportunityBySalesRepDTO;
import com.ironhack.manageAllservice.controller.dtos.report.ReportDTO;
import com.ironhack.manageAllservice.service.exceptions.SalesRepNotFoundException;
import com.ironhack.manageAllservice.controller.dtos.report.*;
import com.ironhack.manageAllservice.service.interfaces.IManageAllService;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
#Service
public class ManageAllService implements IManageAllService {
#Autowired
private CircuitBreakerFactory circuitBreakerFactory;
#Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowSize(2)
.ignoreExceptions(SalesRepNotFoundException.class)
.build();
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.circuitBreakerConfig(circuitBreakerConfig)
.timeLimiterConfig(timeLimiterConfig)
.build());
}
public SalesRepDTO getSalesRepById(Integer id) {
CircuitBreaker circuitBreaker = circuitBreakerFactory.create("salesRep-service");
SalesRepDTO salesRepDTO = circuitBreaker.run(()->salesRepClient.getSalesRep(id),
throwable -> postSalesRepFallBack());
return salesRepDTO;
}
SalesRepNotFoundException.class is the exception I want to ignore, but the circuitbreaker isn't changing the configuration. Any suggestion?
I suggest that you have a look at our Spring Boot 2 starter: https://resilience4j.readme.io/docs/getting-started-3
Our Spring Boot starter allows you to extract the configuration into the config file and use annotations.

Java spring boot AuthenticationManager injection faild

I am trying to implement the JWT authentication found here. here
While running I got the following error:
Field authenticationManager in controllers.SecurityController required
a bean of type
'org.springframework.security.authentication.AuthenticationManager'
that could not be found.
Field authenticationManager in controllers.SecurityController required
a bean of type
'org.springframework.security.authentication.AuthenticationManager'
that could not be found.
Action:
Consider defining a bean of type
'org.springframework.security.authentication.AuthenticationManager' in
your configuration.
Here is my controller:
package controllers;
import common.ServiceObjectResponse;
import entity.UserEntity;
import enums.Role;
import exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import request.LoginRequest;
import request.RegisterRequest;
import security.JwtTokenProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import services.IUserService;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
#RestController
#Api(tags = "diak", value = "SecurityService")
public class SecurityController
{
#Autowired
private JwtTokenProvider jwtTokenProvider;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private IUserService _userService;
#ApiOperation(value = "login", nickname = "login", tags = "login")
#PostMapping("/api/login")
#ResponseBody
public String Login(#RequestBody #Valid LoginRequest data) throws Exception
{
ServiceObjectResponse<UserEntity> request = _userService.findByCredentials(data.Email, data.Jelszo);
if(!request.getIsSuccess())
{
throw new Exception(request.getMessage());
}
else if(request.getIsSuccess() && request.getObject() == null)
{
throw new Exception("No user found with given credantials!");
}
UserEntity user = request.getObject();
try
{
UsernamePasswordAuthenticationToken authenticationData = new UsernamePasswordAuthenticationToken(data.Email, data.Jelszo);
authenticationManager.authenticate(authenticationData);
List<Role> roles = new ArrayList<>();
roles.add(enums.Role.valueOf(user.Role));
return jwtTokenProvider.createToken(user.UniqID, roles);
}
catch (AuthenticationException e)
{
throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
return jwtTokenProvider.createToken(user.UniqID, roles);
}
}
Am not good with java. If anyone can help.
thnx

org.springframework.http.converter.HttpMessageNotReadableException when running JUnit/Mockito Tests

Im running a JUnit test with Mockito in my Spring Boot application. I am mocking the repository which the controller is supposed to call. I am getting a HttpMessageNotReadableException when running the POST test with a response code of 400 (The GET works fine).
package coffee;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.*;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import coffee.controller.AboutController;
import coffee.data.AboutRepository;
#RunWith(SpringRunner.class)
#WebMvcTest(value = AboutController.class, secure = false)
public class AboutControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private AboutRepository aboutRepository;
List<About> res;
#Before
public void setUp() {
res = new ArrayList<About>();
About about = new About();
about.setName("Test");
res.add(about);
}
#Test
public void postAbouts() throws Exception{
About about = res.get(0);
Mockito.when(aboutRepository.save(about))
.thenReturn(about);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/abouts")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content("{'id':null,'position':null,'name':'Test','description':null,'image':null}");
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().isOk())
.andReturn();
JSONAssert.assertEquals("{'id':null,'position':null,'name':'Test','description':null,'image':null}",
result.getResponse().getContentAsString(),
false);
}
}
MockHttpServletRequest:
HTTP Method = POST
Request URI = /abouts
Parameters = {}
Headers = {Content-Type=[application/json], Accept=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = coffee.controller.AboutController
Method = public coffee.About coffee.controller.AboutController.postAbout(coffee.About)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
2019-05-21 14:47:56.035 INFO 1977 --- [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#7fd50002: startup date [Tue May 21 14:47:54 PDT 2019]; root of context hierarchy
Here is the controller that is being tested
package coffee.controller;
import coffee.*;
import coffee.data.AboutRepository;
import java.util.Optional;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping(path="abouts",
produces="application/json",
consumes="application/json")
#CrossOrigin(origins="*")
public class AboutController {
private AboutRepository aboutRepo;
public AboutController(AboutRepository aboutRepo) {
this.aboutRepo = aboutRepo;
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public About postAbout(#RequestBody About about) {
return aboutRepo.save(about);
}
}
it looks like the About json is invalid. Can you try with json with double quotes on the content method ?
{ "id":null, "position":null, "name":"Test", "description":null, "image":null }

SpringBootTest with RANDOM_PORT in Spring Boot 2.1.1 is using 8080 every time

I have a test class that is running in Spring Boot 2.1.1 and Java 11 and no matter what I do, it runs on port 8080:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#RunWith( SpringJUnit4ClassRunner.class )
#SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = TestClass.Config.class
)
#ContextConfiguration(
classes = TestClass.Config.class
)
#TestPropertySource( properties = "server.port=0" )
public class TestClass
{
#LocalServerPort
private String port;
#Test
public void testPort() throws Exception
{
mockMvc
.perform(
MockMvcRequestBuilders.get( "/" )
)
.andExpect( MockMvcResultMatchers.status().isOk() );
}
#Configuration
#RestController
public static class Config
{
#Bean
ServletWebServerFactory servletWebServerFactory()
{
return new TomcatServletWebServerFactory();
}
#GetMapping( "/" )
public String test(HttpServletRequest request, HttpServletResponse response)
{
//This still shows no random port
System.out.println( request.getLocalPort() );
return "ok";
}
}
}
Even when I try this:
#Bean
ServletWebServerFactory servletWebServerFactory()
{
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort( SocketUtils.findAvailableTcpPort() );
return factory;
}
which does result in the field port as having a random port number, MockMvc still uses the default port for my controller.
How can I get it to use a random port?
Try setting the port to 0 , it worked for me.
#Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory(0);
}
Running the test twice produces 2 different random ports.
63957
64043
Try this. You are free to use TestRestTemplate instead of RestAssured and MockBean as required
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import io.restassured.RestAssured;
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BookIT_SpringBootTest_WithWebServerAndRestAssured {
#LocalServerPort
private int port;
#Test
public void myTest() {
RestAssured
.given()
.baseUri("http://localhost/api")
.port(port)
.queryParam("id", "1")
.when()
.get("/book/get-book-id")
.then()
.statusCode(200);
}
}

Spring Test - Mock #ModelAttribute

I have a RestController that I'm attempting to test via Spring MVC Test. It has the following ModelAttribute in it:
#ModelAttribute("authUser")
public User authUser(#AuthenticationPrincipal SpringAuthUser springAuthUser) throws Exception {
User user = ConstantsHome.userprofileMgr.getUserByUserId(springAuthUser.getUsername(), true, true);
user.updateRights(null);
request.getSession().setAttribute(ConstantsHome.USEROBJECT_KEY, user);
return user;
}
When I run a test against this RestController, I'm getting a NullPointerException inside this authUser method.
Is there a way to mock this method such that the mocked method gets used instead of this one for testing? I've read other posts on this and thought I could just pass an "authUser" param in my test but that's not working. Ultimately trying to make this "authUser" not throw an NPE...here is my test...
#Test
public void testGetAllUsers() throws Exception {
String userJson = AvadaObjectMapper.getMapper().writeValueAsString(new User());
System.out.println("userJson=" + userJson);
MvcResult result = this.mockMvc.perform(get("/").param("authUser", userJson).accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andDo(print())
.andReturn();
String content = result.getResponse().getContentAsString();
assertTrue(content.contains("Hello"));
}
I was able to get my authUser to work via the test configuration class below. Pay attention to the .defaultRequest... line in particular as that is where the auth user gets established. I use the class below as the #ContextConfiguration class on all of my tests.
import com.avada.rest.api.users.UserService;
import com.avada.rest.api.users.TestUserService;
import com.avada.rest.security.SpringAuthUser;
import java.util.HashSet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#Configuration
#ComponentScan(excludeFilters={
#ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=UserService.class)
})
public class TestSpringRestConfig {
public static final SpringAuthUser AUTH_USER =
new SpringAuthUser("test", "test",
new HashSet<GrantedAuthority>() {{
add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}}
);
#Bean
public UserService userService() {
return new TestUserService();
}
#Bean
public MockMvc mockMvc(WebApplicationContext wac) {
return MockMvcBuilders
.webAppContextSetup(wac)
.defaultRequest(MockMvcRequestBuilders.get("/").with(SecurityMockMvcRequestPostProcessors.user(AUTH_USER)))
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
}

Categories