Spring Boot - connect resource server to Spring Session with an Redis server - spring-boot

For evaluation purposes we would like to use Spring Session in combination with an Embedded-Redis server.
When using Spring Boot 2.6.7 with JDK17 we start the Spring Session with an Embedded-Redis server. The server is started just after the 'UI' server. The code and config is given at the end.
The 'resource' server that is receiving the Spring Session token cannot connect to redis.
The resource server code is:
#SpringBootApplication
#RestController
public class ResourceApplication extends WebSecurityConfigurerAdapter {
private final static Logger logger = LoggerFactory.getLogger(ResourceApplication.class);
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests().anyRequest().authenticated();
}
#RequestMapping("/")
#CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = { "x-auth-token", "x-requested-with", "x-xsrf-token" })
public Message home() {
logger.info( "ResourceServer: home()");
return new Message("Hello World");
}
#Bean
HeaderHttpSessionStrategy sessionStrategy() {
return new HeaderHttpSessionStrategy();
}
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
}
The properties are:
security.sessions=NEVER
spring.session.store-type=redis
spring.redis.host=localhost
spring.redis.port=6379
The dependencies are:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
When adding e.g. the spring-session-data-redis
The error message is:
An attempt was made to call a method that does not exist. The attempt
was made from the following location:
org.springframework.boot.autoconfigure.session.RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.customize(RedisSessionConfiguration.java:80)
When adding the spring-sessions-data-redis dependency, gives the same error message.
Only for your information, starting up the Redis-embedded server goes like this:
#SpringBootApplication
#EnableWebSecurity
public class DemoApplication {
private Logger logger = LoggerFactory.getLogger(getClass());
private RedisServer redisServer;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#PostConstruct
public void startRedis() throws IOException {
try {
redisServer = RedisServer.builder().setting("maxheap 256Mb").port(6379).build();
redisServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#PreDestroy
public void stopRedis(){
redisServer.stop();
}
}
Dependencies:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.7.3</version>
</dependency>
The resources:
spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379
spring.session.store-type=redis

Related

Feign Client with Spring Cloud GatewayFilter cause cycle dependency

During certain checks, I need to make a request to my Microservice in the Gateway Filter.
When I define the Feign class in the GatewayFilter(my SecurityFilter.java) class, it gives the following error.
How can I resolve this situation.
Error:
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| securityFilter defined in file [/target/classes/com/example/SecurityFilter.class]
↑ ↓
| cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
↑ ↓
| routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
└─────┘
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
GatewayFilter class
#Component
public class SecurityFilter implements GatewayFilterFactory<SecurityFilter.Config> {
private final UserApi userApi;
public SecurityFilter(UserApi userApi) {
this.userApi = userApi;
}
#Override
public GatewayFilter apply(Config config) {
return ((exchange, chain) -> {
return chain.filter(exchange.mutate().request(exchange.getRequest()).build());
});
}
#Override
public Class<Config> getConfigClass() {
return Config.class;
}
#Override
public Config newConfig() {
Config c = new Config();
return c;
}
public static class Config {
}
}
pom.xml
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Main class
#SpringBootApplication
#ComponentScan("com.example")
#EnableFeignClients(basePackages = {"com.example.feign"})
public class GatewayApplicationMain {
public static void main(String[] args) {
SpringApplication.run(GatewayApplicationMain.class, args);
}
}
Feign api class
#FeignClient(name = "user", path="userService/", url="http://localhost:8091/")
public interface UserApi {
#GetMapping("/getUserByUserName/{userName}")
ResponseEntity<Object> getUserByUserName(#PathVariable(name = "userName") String userName);
}
Security class
#Configuration
public class SecurityConfig {
#Bean
public SecurityWebFilterChain configure(ServerHttpSecurity http) {
http.csrf().disable()
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login()
.and().oauth2ResourceServer().jwt();
return http.build();
}
}
application.properties file
server.port=8090
spring.main.allow-circular-references=true
private final UserApi userApi;
#Autowired
public SecurityFilter(#Lazy UserApi userApi) {
this.userApi = userApi;
}
This is how I was able to fix the problem by adding #Lazy.
If you intend to keep the circular dependency you can add this configuration
spring.main.allow-circular-references: true
I'm using #Lazy annotation whenever the feign client intent to be use, to avoid Circular Reference Error when using spring-cloud-gateway along with OpenFeign, even in my CustomGatewayFilter :)
#Component
public class CustomApiGatewayFilter extends AbstractGatewayFilterFactory<CustomApiGatewayFilter.Config> {
private static Logger logger = LogManager.getLogger(CustomApiGatewayFilter.class);
private final JwtConfig jwtConfig;
private final ThirdPartyFeignClientService thirdPartyFeignClientService;
public CustomApiGatewayFilter(JwtConfig jwtConfig, #Lazy ThirdPartyFeignClientService thirdPartyFeignClientService) {
super(Config.class);
this.jwtConfig = jwtConfig;
this.thirdPartyFeignClientService = thirdPartyFeignClientService;
}
....
....
}
And the usage of this feign client placed on a separate function used by this filter
private String validateToken(String jwtToken) throws MyAppException {
String json = "";
ObjectMapper mapper = new ObjectMapper();
try {
Claims claims = jwtConfig.getAllClaimsFromToken(jwtToken);
String additionalInfo = (String) claims.get("additionalInfo");
JwtPayload payload = mapper.readValue(additionalInfo, JwtPayload.class);
String username = jwtConfig.getUsernameFromToken(jwtToken);
if(thirdPartyFeignClientService.validateClient(payload.getClientId(), payload.getClientSecret())){
return username;
}else{
throw new MyAppException("Invalid Client", ErrorCode.GENERIC_FAILURE);
}
} catch (ExpiredJwtException e) {
logger.error(e.getMessage());
throw new MyAppException(e.getMessage(), ErrorCode.GENERIC_FAILURE);
} catch (Exception e) {
logger.error("Other Exception :" + e);
throw new MyAppException (e.getMessage(), ErrorCode.GENERIC_FAILURE);
}
}
And it works :)

How to make springboot register a RestController?

I havent worked too much with Spring API tools before, have more experience with Jersey. I have looked at many different articles explaining how to get REST endpoints wired up with Springboot and I just dont see why this is not working.
Here are some relevant code snippets:
In application.properties
server.port=5000
The package is com.myproj
#SpringBootApplication(scanBasePackages={"com.myproj"})
public class ClaimsIntakeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ClaimsIntakeServiceApplication.class, args);
}
}
In com.myproj.controllers
#Controller
#RequestMapping(value = "/hello")
public class ClaimController {
#GetMapping
public ResponseEntity<Item> read() {
System.out.println("hi");
return new ResponseEntity<>("", HttpStatus.OK);
}
If i hit this URL in postman: https://localhost:5000/hello ..
It says
connection refused
How do I wire up a rest endpoint with springboot so I can hit it with postman as shown above?
Something like this should work:
Main class:
#SpringBootApplication
#ComponentScan(basePackages = {"com.myproj"})
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
Controller:
#RestController
public class HelloWorldController {
#RequestMapping(path = "/hello-world", method = RequestMethod.GET, produces =
MediaType.APPLICATION_JSON_VALUE)
public HelloWorldResponse getHelloWorld() {
return new HelloWorldResponse("hello!!");
}
}
Docs here
For some reason while i get all the stuff for API with this:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-cosmosdb-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
I had to include this as well in order for the API to work:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

The AOuth2 Authorization server does not insert token in the given database

There is some configuration class in Authorization server:
#Configuration
public class AppConfig {
#Value("${spring.datasource.url}")
private String datasourceUrl;
#Value("${spring.database.driverClassName}")
private String dbDriverClassName;
#Value("${spring.datasource.username}")
private String dbUsername;
#Value("${spring.datasource.password}")
private String dbPassword;
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbDriverClassName);
dataSource.setUrl(datasourceUrl);
dataSource.setUsername(dbUsername);
dataSource.setPassword(dbPassword);
return dataSource;
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource());
}
}
and the another class:
#EnableWebSecurity
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private AccountUserDetailsService accountUserDetailsService;
#Bean
public PasswordEncoder passwordEncoder() {
return new HashingClass();
}
#Bean
#Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return accountUserDetailsService;
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**", "/resources/**");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean())
.passwordEncoder(passwordEncoder());
}
}
and the third class is:
#EnableAuthorizationServer
#Configuration
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
private final AuthenticationManager authenticationManager;
private final AppConfig appConfig;
#Autowired
public AuthServerOAuth2Config(AuthenticationManager authenticationManager, AppConfig appConfig) {
this.authenticationManager = authenticationManager;
this.appConfig = appConfig;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(appConfig.dataSource());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
/*
* Allow our tokens to be delivered from our token access point as well as for tokens
* to be validated from this point
*/
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");;
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(appConfig.tokenStore()); // Persist the tokens in the database
}
}
and the client application is like this:
#SpringBootApplication
#EnableOAuth2Sso
#RestController
#Configuration
public class SocialApplication extends WebSecurityConfigurerAdapter {
#Value("${security.oauth2.client.clientId}")
private String clientId;
#Value("${security.oauth2.client.clientSecret}")
private String clientSecret;
#Value("${security.oauth2.client.accessTokenUri}")
private String accessTokenUri;
#RequestMapping("/user")
public Principal user(HttpServletResponse response, Principal principal) {
return principal;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**", "/index.html", "/getEmployees.jsp").permitAll()
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
#Bean
public OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
details.setClientId(clientId);
details.setClientSecret(clientSecret);
details.setAccessTokenUri(accessTokenUri);
return details;
}
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
}
and its application.yml file is:
server:
port: 8090
security:
basic:
enabled: false
oauth2:
client:
clientId: web
clientSecret: secret
accessTokenUri: http://localhost:8081/auth/oauth/token
userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: http://localhost:8081/auth/user
logging:
level:
org.springframework.security: DEBUG
When I request http://localhost:8090/user (this rest is owned client) I redirected to Authorization server and I can login successfully after login again I am redirected to the client with a code, but client is not able to exchange access token with the given code. and the following exception is raised on the browser:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback. Mon Dec 17 09:47:27 IRST 2018 There was an
unexpected error (type=Unauthorized, status=401). Authentication
Failed: Could not obtain access token
And I query from DB:
select * from oauth_access_token
or
select * from oauth_client_token
The two above tables are empty.
Where is wrong? I am really confused.
EDIT
The application.properties file of AOuthrization server:
server.port=8081
server.context-path=/auth
security.basic.enabled=false
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database w/createDatabaseIfNotExist=true
spring.datasource.url = jdbc:oracle:thin:#192.168.192.129:1521:hamed
spring.database.driverClassName = oracle.jdbc.OracleDriver
#spring.jpa.database = MySQL
#spring.datasource.platform = mysql
# Database - data initialization
spring.jpa.generate-ddl = true
# Username and password
spring.datasource.username = test
spring.datasource.password = test
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Transactions
spring.jpa.open-in-view = false
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = none
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle12cDialect
and the its pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r05</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0</version>
</dependency>
</dependencies>
and the version of spring boot is:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
I noticed you are using spring-boot and to me seems like you can clean up your code a little, for instance, all this DataSource config may not be necessary.
As for your problem, it could be related to the class AuthServerOAuth2Config where you are injecting AppConfig instead of DataSource and TokenStore, making this change can solve your problem.
Here you can find a sample auth service I did a while ago https://github.com/marcosbarbero/spring-security-authserver-sample
I could solve my problem by removing two lines of application.yml of client application.
These two lines are:
authenticationScheme: query
clientAuthenticationScheme: form
Why these two lines cause problem, I do not know.

How to create filter in Spring RESTful for Prevent XSS?

i use from Spring 4.2.6.RELEASE and backend is rest services.
and now I can not have a filter for Prevent XSS
my filter is:
#Component
#Order(1)
public class XSSFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
}
}
and XSSRequestWrapper is :
public class XSSRequestWrapper extends HttpServletRequestWrapper {
public XSSRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
#Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = stripXSS(values[i]);
}
return encodedValues;
}
#Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
return stripXSS(value);
}
#Override
public String getHeader(String name) {
String value = super.getHeader(name);
return stripXSS(value);
}
private String stripXSS(String value) {
return StringEscapeUtils.escapeHtml(value);
}
}
and in WebConfig extends WebMvcConfigurerAdapter Class:
// -----------------------------------------------------
// Prevent XSS
// -----------------------------------------------------
#Bean
public FilterRegistrationBean xssPreventFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new XSSFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
My Rest Class is:
#RestController
#RequestMapping("/personService")
public class PersonController extends BaseController<PersonDto, PersonCriteria> {
#RequestMapping( value= "/test" )
private void getTest2(#RequestParam String name) {
System.out.println(name);
System.out.println( StringEscapeUtils.escapeHtml(name) );
}
}
But it does not work, without any Error or Exception.
How can I do this and create my own filter? I use only Java Config and no XML.
in my Controller I was forced again use StringEscapeUtils.escapeHtml(name) and this is bad.
I’ve created a fully executable sample project based on your codes.
Everything goes fine, you can download full source from my github https://github.com/mehditahmasebi/spring/tree/master/spring-xss-filter and for running command “mvnw spring-boot:run” and in browser type: http://localhost:8080/personService/test?name=foobar, so you can see result in XSSRequestWrapper.stripXSS.
I hope this source code will help you.
Some explanation :
Project structure :
POM.xml
WebConfig.java for Spring web config
SpringBootApplication.java for starting up application
your classes (PersonController.java, XSSFilter.java and XSSRequestWrapper.java)
dive into them, but I was only copy important lines :
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
WebConfig.java (at the bottom lines you can see your bean) :
#Configuration
#EnableWebMvc
#EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("GET, POST, PATCH, PUT, DELETE, OPTIONS")
.allowedOrigins("*");
}
#Bean
public FilterRegistrationBean xssPreventFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new XSSFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
SpringBootApplication.java (for starting up project) :
#SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {
/**
* tomcat deployment needed
*/
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
System.out.println("Spring boot application started!");
}
}
The other java source files is exactly as you are , but with 2 changes :
first, I've added a sysout line to see trace of your code without debugging:
private String stripXSS(String value) {
if(value != null)
System.out.println("escapeHTML work successfully and escapeHTML value is : " + StringEscapeUtils.escapeHtml(value));
return StringEscapeUtils.escapeHtml(value);
}
and the second change is, I commented escapeHtml from PersonController as you said is not a good idea:
#RequestMapping( value= "/test" )
private void getTest2(#RequestParam String name) {
System.out.println(name);
// System.out.println( StringEscapeUtils.escapeHtml(name) );
}
You can find all the source at my github https://github.com/mehditahmasebi/spring/tree/master/spring-xss-filter

SpringBoot: how to test if the service is up and running using rest-assured

In my spring boot application how can I test if the service is up and running using rest assured. the main() is defined like this -
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Your test should look like this
public class ApplicationTest {
#Before
public void setup() {
RestAssured.baseURI = "http://localhost:8080";
}
#Test
public void testStatus() {
given().contentType(ContentType.JSON).get("/greeting").prettyPeek().then().statusCode(200);
}
#Test
public void testMessage() {
given().contentType(ContentType.JSON).get("/greeting").then()
.body("content", is("Hello, World!"));
}
}
Include dependency below in your build tool:
Gradle:
testCompile('com.jayway.restassured:rest-assured:2.4.1')
Maven:
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.4.1</version>
</dependency>

Resources