Spring Security 403 http status - rest

I am implementing Spring Security on a Spring Boot 2.0.1 project.
I have some web services that used to work fine before Spring Security implementation. But now, they don't.
This is the error message displayed in REST client.
{
"timestamp": "2018-07-27T11:14:40.080+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/lsm/notification/getCurrentUserNotifications"
}
and the same error on google chrome :
Below is the controller listing the services:
package com.sap.lsm.web;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sap.lsm.dao.NotifiedUserRepository;
import com.sap.lsm.dao.UserNotificationRepository;
import com.sap.lsm.entities.NotifiedUser;
import com.sap.lsm.entities.UserNotification;
import com.sap.lsm.service.UserNotificationService;
#RestController
public class UserNotificationController {
#Autowired
private UserNotificationService userNotificationService;
#Autowired
private UserNotificationRepository userNotificationRepository;
#RequestMapping(value="/notification/getCurrentUserNotifications", method=RequestMethod.GET)
public List<UserNotification> getCurrentUserNotifs() {
return userNotificationService.getCurrentUserAllNotifications();
}
#RequestMapping(value="/notification/getCurrentUserNotSeenNotifications", method=RequestMethod.GET)
public List<UserNotification> getCurrentUserNotSeenNotifs() {
return userNotificationService.getCurrentUserNotSeenNotifications();
}
#RequestMapping(value="/notification/deleteNotification/{id}", method=RequestMethod.DELETE)
public void deleteNotification(#PathVariable("id") Long id){
userNotificationService.deleteNotification(id);
}
#RequestMapping(value="/notification/getNotification/{id}", method=RequestMethod.GET)
public UserNotification getNotification(#PathVariable("id") Long id) {
UserNotification notification = this.userNotificationService.getNotification(id);
if(!notification.equals(null)) {
notification.setStatus("seen");
userNotificationRepository.save(notification);
}
return notification;
}
#RequestMapping(value="/notification/markCurrentUserNotificationsAsSeen", method=RequestMethod.GET)
public void markCurrentUserNotificationsAsSeen() {
userNotificationService.markAllNotificationsAsSeen();
}
}
And this is the Spring Security Config :
package com.sap.lsm.config;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#EnableGlobalMethodSecurity(prePostEnabled=true)
#EnableWebSecurity
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private RequestFilter requestFilter;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public SpringSecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.logout().deleteCookies("JSESSIONID").invalidateHttpSession(true)
.and()
.authorizeRequests()
.antMatchers("/lsm/listCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/addCustomer").hasAnyAuthority("CONSULTANT")
.antMatchers("/lsm/getAllCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/getOldCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/getCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/getCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/deleteCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/cancelCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/restoreCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/updateCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/getLSMUsers").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/addLSMUser").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/getLSMUser/*").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/deleteLSMUser/*").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/cancelLSMUser/*").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/restoreLSMUser/*").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/updateLSMUser/*").hasAnyAuthority("ADMIN")
.antMatchers("/lsm/notification/getCurrentUserNotifications/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/notification/getCurrentUserNotSeenNotifications/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/notification/deleteNotification/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/notification/getNotification/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/lsm/notification/markCurrentUserNotificationsAsSeen/*").hasAnyAuthority("ADMIN","CONSULTANT")
.antMatchers("/assets/**","/login","/*").permitAll()
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilterBefore((Filter) new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(requestFilter, ChannelProcessingFilter.class);
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
If you need JWT authentication and authorization filters, i'll post them later on .
Please help me,
Thanks
** update **
The role of the connected user is ADMIN.
The path /lsm is declared as property in the pom.xml as follows:
<m2eclipse.wtp.contextRoot>/lsm</m2eclipse.wtp.contextRoot>
This root path is used to run the application under Jenkins (integration server)

Related

how avoid to access to other data users. Spring boot + MongoDB

I'm developing a web application with Spring Boot and MongoDB. I'm following the MVC model.
I have a view which shows a list of stored data, but the app ignores the logged user and shows every objects.
https://i.stack.imgur.com/zl7TC.png
Here, the first row was added by another user, but it's showed anyway.
How could I get only the object allowed to the authenticated user?.
The only way I can see is checking the user Id after each query and get only the object of the given user. I think that there should be a better way to do this.
The code is the following:
Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "trackings")
public class Tracking extends Entity implements Serializable {
private static final long serialVersionUID = -1249902722123443448L;
#Indexed(unique = true, direction = IndexDirection.DESCENDING)
private String trackingName;
private String SoftwareName;
#DBRef
private Set<Alarm> alarms;
public String getTrackingName() {
return trackingName;
}
public void setTrackingName(String trackingName) {
this.trackingName = trackingName;
}
public String getSoftwareName() {
return SoftwareName;
}
public void setSoftwareName(String softwareName) {
SoftwareName = softwareName;
}
public Collection<Alarm> getAlarms() {
return alarms;
}
public void setAlarms(Set<Alarm> alarms) {
this.alarms = alarms;
}
}
Repository
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import us.etsii.fvt.domains.Tracking;
#Repository
public interface TrackingRepository extends MongoRepository<Tracking, String>{
Tracking findByTrackingName(String name);
}
Controller
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import us.etsii.fvt.domains.Alarm;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.domains.User;
import us.etsii.fvt.services.TrackingService;
import us.etsii.fvt.services.UserService;
#Controller
public class TrackingController {
#Autowired
private UserService userService;
#Autowired
private TrackingService trackingService;
#RequestMapping(value = { "/tracking" }, method = RequestMethod.GET)
public ModelAndView tracking() {
ModelAndView modelAndView = new ModelAndView();
// AƱadimos el usuario al modelo
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("currentUser", user);
modelAndView.addObject("fullName", user.getFullname());
// AƱadimos la lista de trackings al modelo
List<Tracking> trackings = trackingService.findAll();
modelAndView.addObject("trackings", trackings);
// Devolvemos el modelo
modelAndView.setViewName("tracking");
return modelAndView;
}
...
}
Service
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.repositories.TrackingRepository;
#Service
public class TrackingService {
#Autowired
private TrackingRepository trackingRepository;
public Tracking findTrackingByName(String name) {
return trackingRepository.findByTrackingName(name);
}
public void saveTracking(Tracking tracking) {
trackingRepository.save(tracking);
}
public List<Tracking> findAll() {
return trackingRepository.findAll();
}
public Tracking findById(String id) {
Optional<Tracking> t = trackingRepository.findById(id);
if(!t.isPresent()) {
return null;
}
return t.get();
}
public void remove(String id) {
trackingRepository.deleteById(id);
}
}
There are ambiguous points in your question but assuming you have an User Entity:
You should get the logged in user from Spring Security
You should include a relation of User Entity to Tracking Entity (include User ID information in Tracking records)
Then you should query the mongo db Tracking Entity with the given user id.
You can use standard query by field functionality of Spring Repository.

HikariCP for MongoDB in springboot

I am looking to create a connection pool - for mongoDB in Springboot. I am currently making use of Springdata Mongo repositories to connect to DB and collections but unsure of how to create the datapool connection
Here is the current implementation
PersonRepository.java
package com.test.TestAPI.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.test.TestAPI.dto.Person;
#Repository
public interface PersonRepository extends MongoRepository<Person, String> {
}
PersonService
package com.test.TestAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Service
public class PersonService {
#Autowired
private PersonRepository personRepo;
public List<Person> findAllPersons() {
return personRepo.findAll();
}
public Person createPerson(Person person) {
return personRepo.save(person);
}
}
PersonController
package com.test.TestAPI.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.TestAPI.service.impl.PersonService;
import com.test.TestAPI.dto.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#RestController
#RequestMapping(path="/v1/personController")
#Api(value="Controller for Person document")
public class PersonController {
#Autowired
PersonService service;
#GetMapping("/getAllPersons")
#ApiOperation(produces = MediaType.APPLICATION_JSON_VALUE, httpMethod = "GET", response = List.class,
value = "getAllPersons from the database", notes = "Sample note")
public ResponseEntity<List<Person>> getAllPersons(){
List<Person> personList = service.findAllPersons();
return new ResponseEntity<List<Person>>(personList, HttpStatus.OK);
}
}
SimpleCommandLineConfig
package com.test.TestAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Component;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Component
#Order(3)
public class SimpleCommandLineConfig implements CommandLineRunner {
#Autowired
PersonRepository repo;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("third command line runner");
System.out.println(repo.save(new Person("rr","rr",4)));
}
}
App.java
package com.test.TestAPI.main;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* Hello world!
*
*/
#SpringBootApplication
#ComponentScan(basePackages= {"com.test.TestAPI"})
#EnableMongoRepositories(basePackages= {"com.test.TestAPI.repository"})
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
Also, I would like to know if spring data repos like a custom repo for MongoDB takes care of connection pool mechanism? How does connection pooling happen in that case? Could you please help me on this
I think I found an answer for this. Just like we use JDBC templates for RDBMS to store the databases, spring provides something called MongoTemplates which forms a connection pool based on the db configuration given
Here is a sample implementation
MongoClientFactory.java
public #Bean MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
.connectionsPerHost(2000)
.connectTimeout(4000)
//.maxConnectionIdleTime(1000000000)
.maxWaitTime(3000)
.retryWrites(true)
.socketTimeout(4000)
.sslInvalidHostNameAllowed(true)//this is very risky
.build();
mongo.setMongoClientOptions(clientOptions);
return mongo;
}
DataSourceConfig.java (Another config class. Same config class can also be used to define all beans)
package com.fmr.FeedBackAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
#Configuration
#Import(value=MongoClientFactory.class)
public class DataSourceConfig {
#Autowired
Mongo mongo;
#Autowired
Environment env;
#Bean
public String test() {
System.out.println("mongo"+mongo);
return "rer";
}
private MongoTemplate mongoTemplate() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
MongoTemplate template = new MongoTemplate(factory);
return template;
}
#Bean
#Qualifier(value="customMongoOps")
public MongoOperations mongoOps() {
MongoOperations ops = mongoTemplate();
return ops;
}
#Bean
public MongoDbFactory factory() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
return factory;
}
// #Bean
// public GridFsTemplate gridFsTemplate() {
// return new GridFsTemplate(mongo, converter)
// }
#Bean
public javax.sql.DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(100);
// ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
// ds.setJdbcUrl(env.getProperty("spring.datasource.url"));;
//ds.setUsername(env.getProperty("spring.datasource.username"));
//ds.setPassword(env.getProperty("spring.datasource.password"));
ds.addDataSourceProperty("cachePrepStmts", true);
ds.addDataSourceProperty("prepStmtCacheSize", 250);
ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
ds.addDataSourceProperty("useServerPrepStmts", true);
return ds;
}
}
Now autowire the template/mongoOperations in you dao implementation or service and use it
package com.fmr.FeedBackAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.fmr.FeedBackAPI.dto.ConfigDTO;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
#Service
public class PlanConfigService {
#Autowired
#Qualifier(value="customMongoOps")
MongoOperations mongoOps;
public List<ConfigDTO> createConfigDTOList(List<ConfigDTO> configDTOList) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.insert(configDTOList, ConfigDTO.class);
configList = mongoOps.findAll(ConfigDTO.class, "ConfigDTO_table");
return configList;
}
public List<ConfigDTO> createConfigDTO(ConfigDTO configDTO) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.save(configDTO);
configList = mongoOps.find(query(where("planId").is(configDTO.getPlanId())), ConfigDTO.class,"ConfigDTO_table");
return configList;
}
}
Here is the application.properties (this is the default instance running in local)
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mongo_test
spring.data.mongodb.repositories=true
#
spring.datasource.url=jdbc:mongodb://localhost:27017/mongo_test

ContainerRequestFilter method not being called on WAS liberty

I have filter class on my WAS Liberty server:
// TestRequestFilter.java
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
#Secured
#Provider
#PreMatching
public class TestRequestFilter implements ContainerRequestFilter
{
private final static Logger log = Logger.getLogger(DemoRESTRequestFilter.class.getName());
#Override
public void filter(ContainerRequestContext requestCtx) throws IOException
{
System.out.println("FILTER-REQUEST");
}
}
And custom annotation:
#NameBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE, ElementType.METHOD })
public #interface Secured {
}
And a rest call:
#GET
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
#Secured
public Response login(#HeaderParam("Authorization") String authorization) {
return Response.ok("OK").build();
}
Server.xml:
<!-- Enable features -->
<featureManager>
<feature>javaee-7.0</feature>
<feature>localConnector-1.0</feature>
<feature>appSecurity-2.0</feature>
</featureManager>
How to make Filter work on a WAS ?
You need to register TestRequestFilter:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
#ApplicationPath("/")
public class RestApplication extends Application
{
#Override
public Set<Object> getSingletons()
{
Set<Object> singletons = new HashSet<>();
singletons.add(new TestRequestFilter());
// register others, if any
return singletons;
}
}

Why I receive error when use Cover As in Eclipse and not with Junit?

I use Eclipse with eCobertura
I have a little project with a Controller (SpringMVC).
I created a test (JUnit).
When I run the test from JUnit (in Eclipse IDE) all is right but when I run the command (from menu) I receive an error
My controller :
package ec.europa.eu.nwi.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* #author LEBRUJA
*/
#Controller
public class AvailibilityController {
/**
* #param request
* #return mav
*/
#RequestMapping(value = "/available")
public final ModelAndView available(final HttpServletRequest request) {
final ModelAndView mav = new ModelAndView("available", "sample",
new String("availability on 0.0.1"));
return mav;
}
}
My Test :
package ec.europa.eu.nwi.web.controller.test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.ModelAndViewAssert;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ec.europa.eu.nwi.web.controller.AvailibilityController;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:spring-servlet.xml"})
public final class AvalibilityControllerTest {
private transient MockHttpServletRequest request;
private transient MockHttpServletResponse response;
#Autowired
private RequestMappingHandlerAdapter handlerAdapter;
#Autowired
private RequestMappingHandlerMapping handlerMapping;
private static final Logger LOGGER = LoggerFactory.getLogger(AvalibilityControllerTest.class);
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
#After
public void tearDown() throws Exception {
LOGGER.debug("TearDown");
}
#Test
public void testAvailable() {
LOGGER.debug("Start testAvailable1");
LOGGER.debug("Test only availibility of the apps");
final AvailibilityController avc = new AvailibilityController();
final Object mav = avc.available(request);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(mav instanceof ModelAndView);
ModelAndViewAssert.assertAndReturnModelAttributeOfType((ModelAndView)mav, "sample", String.class);
ModelAndViewAssert.assertModelAttributeAvailable((ModelAndView)mav, "sample");
ModelAndViewAssert.assertModelAttributeValue((ModelAndView)mav, "sample", "availability on 0.0.1");
ModelAndViewAssert.assertViewName((ModelAndView)mav, "available");
final BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
LOGGER.debug("End testAvailable1");
}
#Test
public void testAvailable1() throws Exception {
LOGGER.debug("Start testAvailable");
LOGGER.debug("Test only availibility of the apps");
request.setMethod("GET");
request.setRequestURI("/available.html");
Object handler = handlerMapping.getHandler(request).getHandler();
LOGGER.debug("Get the Model and View");
ModelAndView modelAndView = handlerAdapter.handle(request, response,handler);
Assert.assertEquals("availability on 0.0.1", modelAndView.getModel().get("sample"));
Assert.assertTrue(modelAndView.getModel().containsKey("sample"));
LOGGER.debug("End testAvailable");
}
}
If I run with JUnit (Run As Junit), all is right but when I run Cover As .. JUnit I receive the error.
The error :
I filtered the class (from exclude configuration in Eclipse Coverage Configuration).
If I removed the filter, the junit code is marked in red
I don't understand the error.
Thanks a lot
I had
<aop:aspectj-autoproxy proxy-target-class="true" />
In my applicationContext.xml and it is running fine now
Thanks a lot

HTTP Basic Authentication in Restlet with a JAXRS Application?

I'm trying to authenticate access to all resources on my server via HTTP Basic authentication. Currently, my setup looks like this when starting the server:
this.component = new Component();
this.server = this.component.getServers().add(Protocol.HTTP, 8118);
JaxRsApplication application = new JaxRsApplication(component.getContext()
.createChildContext());
application.add(new RestletApplication());
ChallengeAuthenticator authenticator = new ChallengeAuthenticator(
this.component.getContext(),
ChallengeScheme.HTTP_BASIC, "test");
authenticator.setVerifier(new ApplicationVerifier());
this.component.getDefaultHost().attachDefault(authenticator);
this.component.getDefaultHost().attach(application);
this.component.start();
Here's my RestletApplication:
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class RestletApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(TestResource.class);
return classes;
}
}
Here's my ApplicationVerifier:
import java.util.HashMap;
import java.util.Map;
import org.restlet.security.LocalVerifier;
public class ApplicationVerifier extends LocalVerifier {
private Map<String, char[]> localSecrets = new HashMap<String, char[]>();
public ApplicationVerifier() {
this.localSecrets.put("username", "password".toCharArray());
}
#Override
public char[] getLocalSecret(String key) {
if (this.localSecrets.containsKey(key))
return this.localSecrets.get(key);
return null;
}
}
Finally, here's my TestResource:
import java.util.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Path("test")
public class TestResource {
#GET
#Path("list")
public TestList getTestList() {
return makeTestList();
}
}
However, I'm not seeing any prompt or requirement for authentication when I try to access the resource. What am I doing wrong? I'm not having any issues with marshalling and unmarshalling items and I'm sure that my resource is getting hit with requests. What am I not doing right?
According to the JavaDocs for JaxRsApplication, an authenticator can be set using the following code before starting things up:
((JaxRsApplication)application).setGuard((Authenticator)authenticator);
Do that, and all requests will fly through your authenticator :)