Spring boot test : How to test a controller with jpa data - spring-data-jpa

I want to test a controller with jpa data.
How can i do it?
I have this controller :
#RestController
#RequestMapping("/api")
public class AuthenticateController {
#Autowired private AuthenticationManager authenticationManager;
#Autowired private ClientRepository client;
#Autowired private JwtUtil jwt;
#Autowired private UserDetailsService details;
#PostMapping("/authenticate") public ResponseEntity<?> createAuthenticationToken(#RequestBody AuthenticationRequest authenticate) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticate.getIdentification(), authenticate.getPassword()));
}
catch (BadCredentialsException e) { throw new Exception("Incorrect username or password", e); }
final UserDetails userDetails = details.loadUser(authenticate.getIdentification());
final String jwt = this.jwt.generateToken(userDetails);
final String identification = userDetails.getIdentification();
Client c = client.findByUsernameOrEmailOrPhone(identification, identification, identification).orElseThrow();
return ResponseEntity.ok(new AuthenticationResponse(jwt, c));
}
}
and this jpa data
public interface ClientRepository extends JpaRepository<Client, Integer> {
}

Related

Spring boot login with email password

I was developing a backend with spring boot for the first time. I chose email password login over username password login which is the default behavior of spring boot.
I have two objects: AppUser and User. AppUser is used for authentication and User holds every other data necessary for the application.
AppUser:
public class AppUser implements UserDetails {
#Autowired
AuthRepository repository;
#Id
private String id;
#NonNull
#Indexed(unique = true)
#Field(value = "email")
String email;
#NonNull
#Field(value = "password")
String password;
#Field(value = "authorities")
private List<Role> authorities;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> auth = new HashSet<>();
authorities.forEach(index -> auth.add(new SimpleGrantedAuthority(String.valueOf(index.getRole()))));
return auth;
}
#Override
public String getUsername() {
return email;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
AuthController looks like:
#RestController
#RequestMapping("/api/v1/Auth")
public class AuthController {
Logger logger = LoggerFactory.getLogger(AuthController.class);
#Autowired
UserDetailsManager userDetailsManager;
#Autowired
UserService userService;
#Autowired
AuthService authService;
#Autowired
TokenGenerator tokenGenerator;
#Autowired
DaoAuthenticationProvider daoAuthenticationProvider;
#Autowired
#Qualifier("jwtRefreshTokenAuthProvider")
JwtAuthenticationProvider refreshTokenAuthProvider;
#PostMapping("/SignUp")
public ResponseEntity signup(#RequestBody SignUpRequest signUpRequest) {
logger.info(signUpRequest.getUsername());
User user = new User(
signUpRequest.getEmail(),
signUpRequest.getPassword(),
signUpRequest.getUsername(),
signUpRequest.getFirstName(),
signUpRequest.getLastName(),
signUpRequest.getCountry(),
null,
false,
false
);
AppUser appUser = new AppUser(
signUpRequest.getEmail(),
signUpRequest.getPassword()
);
boolean alreadyExists = authService.existsByEmail(signUpRequest.getEmail());
if(alreadyExists){
return ResponseEntity.status(HttpStatus.CONFLICT).body("Email Already Exists");
}else{
userDetailsManager.createUser(appUser);
User newUser = userService.addUser(user);
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(appUser, signUpRequest.getPassword(), Collections.EMPTY_LIST);
return ResponseEntity.ok(tokenGenerator.signup(authentication, newUser));
}
}
#PostMapping("/SignIn")
public ResponseEntity signin(#RequestBody SignInRequest signInRequest) {
logger.info(signInRequest.getEmail());
logger.info(signInRequest.getPassword());
Authentication authentication = daoAuthenticationProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(signInRequest.getEmail(), signInRequest.getPassword()));
logger.info(authentication.getCredentials().toString());
User user = new User();
return ResponseEntity.ok(tokenGenerator.signin(authentication, user));
}
}
The issue is with signin. SignUp works fine when I am providing email and password. Login is not working.
I am quite new so have zero idea where the issue is happening. Any reference code with explanation will help a lot.
Github Link
N.B: using spring boot, mongodb, oauth2
In my understanding based on your WebSecurity.class, your are using OAuth2 authentication.
What I would do is create 2 Configurations inside the same class with a different Order and in the second one a custom AuthenticationProvider. This was Spring will try to authenticate first based on the first class and then on the second one
#Configuration
#EnableWebSecurity
public class SecurityConfiguration {
//here we set as the first in order the below config if this fails the next one in order will be used until any of them succeeds
#Configuration
#Order(1)
public static class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private MyLoginRequestFilter myLoginRequestFilter ;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
http
.antMatchers("/api/v1/Auth/*").permitAll()
.addFilterBefore(myLoginRequestFilter, UsernamePasswordAuthenticationFilter.class )
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.cors()
.disable()
.csrf()
.disable()
;
}
}
Then insert your class below with Order 2 and then close the whole file/class
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Slf4j
#Order(2)
//this is your class that is uploaded in the git. We actually encapsulate inside a generic Security Config class
public class WebSecurity {
#Autowired
JwtToUserConverter jwtToUserConverter;
...
}
} //to close the java class that was started in the previous block of code
You could even add a new function that will handle the HttpSecurity item so that you dont duplicate your code:
public HttpSecurity myHandler(HttpSecurity http) {
return http
.authorizeHttpRequests((authorize) -> authorize
.antMatchers("/api/v1/Auth/*").permitAll()
.antMatchers("/api/v1/Home/*").permitAll()
.anyRequest().authenticated()
)
.csrf().disable()
.cors().disable()
;
}
Note that in the Order(1) example, I have added a filter, but you can leave it without a filter and add a custom AuthenticationProvider with inside the class:
#Autowired
private YourAuthenticationProvider authenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
YourAuthenticationProvider could look like
#Component
public class YourAuthenticationProvider implements AuthenticationProvider {
#Autowired
AuthService authService; //need to move here the authenticate method from the controller Authentication authentication = daoAuthenticationProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(signInRequest.getEmail(), signInRequest.getPassword()));
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final String email = authentication.getName();
final Object credentials = authentication.getCredentials();
if ( credentials == null ) {
return authentication;
}
//I suggest using a password encoder to save the password and then check it with PasswordEncoder (you could create a bean)
final Authentication auth = authService.authenticate(email, credentials.toString());
if (auth != null) {
return auth;
}
throw new BadCredentialsException( "Wrong username and/or password" );
}
}
Hope these help

I am generating JWT token for my spring boot application , but exception is coming

io.jsonwebtoken.security.SignatureException: JWT signature does not match locally computed signature.
I have used the following code . I had to generate JWT in postman client but I am getting this exception
#RestController
#CrossOrigin
public class JwtController {
private final Logger log = LoggerFactory.getLogger(TokenManager.class);
#Autowired
private JwtUserDetailsService userDetailsService;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private TokenManager tokenManager;
#PostMapping("/login")
public ResponseEntity<JwtResponseModel> createToken(#RequestBody JwtRequestModel
request) throws Exception {
try {
authenticationManager.authenticate(
new
UsernamePasswordAuthenticationToken(request.getUsername(),
request.getPassword())
);
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
final String jwtToken = tokenManager.generateJwtToken(userDetails);
return ResponseEntity.ok(new JwtResponseModel(jwtToken));
}
}

MongoRepository Save method does not insert in database

I have created a SpringBoot project with Jhipster. The database I am using is MongoDB.
In the application-dev.yml I have the following configuration:
data:
mongodb:
uri: mongodb://<user>:<pass>#<ip>:<port>
database: gateway
The user, password, ip Address, and port, in my application-dev are real values.
The DatabaseConfiguration.java is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile("!" + JHipsterConstants.SPRING_PROFILE_CLOUD)
#Import(value = MongoAutoConfiguration.class)
#EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(DateToZonedDateTimeConverter.INSTANCE);
converters.add(ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
#Bean
public Mongobee mongobee(MongoClient mongoClient, MongoTemplate mongoTemplate, MongoProperties mongoProperties) {
log.debug("Configuring Mongobee");
Mongobee mongobee = new Mongobee(mongoClient);
mongobee.setDbName(mongoProperties.getMongoClientDatabase());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}}
The CloudDatabaseConfiguration is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
#Bean
public MongoDbFactory mongoFactory() {
return connectionFactory().mongoDbFactory();
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(DateToZonedDateTimeConverter.INSTANCE);
converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
converterList.add(DurationToLongConverter.INSTANCE);
return new MongoCustomConversions(converterList);
}
#Bean
public Mongobee mongobee(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate, Cloud cloud) {
log.debug("Configuring Cloud Mongobee");
List<ServiceInfo> matchingServiceInfos = cloud.getServiceInfos(MongoDbFactory.class);
if (matchingServiceInfos.size() != 1) {
throw new CloudException("No unique service matching MongoDbFactory found. Expected 1, found "
+ matchingServiceInfos.size());
}
MongoServiceInfo info = (MongoServiceInfo) matchingServiceInfos.get(0);
Mongobee mongobee = new Mongobee(info.getUri());
mongobee.setDbName(mongoDbFactory.getDb().getName());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}
}
The cdtiApp.java is:
#SpringBootApplication
#EnableConfigurationProperties({ApplicationProperties.class})
public class CdtiApp implements InitializingBean{
private static final Logger log = LoggerFactory.getLogger(CdtiApp.class);
private final Environment env;
public CdtiApp(Environment env) {
this.env = env;
}
/**
* Initializes cdti.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/.
*/
#PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* #param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CdtiApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info("\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
#Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
The Vehicle entity:
#org.springframework.data.mongodb.core.mapping.Document(collection = "vehicle")
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String id;
#NotNull
#Field("plate")
private String plate;
#NotNull
#Field("registrationDate")
private Instant registrationDate;
#NotNull
#Field("brand")
private String brand;
#NotNull
#Field("model")
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleDTO is:
public class VehicleDTO {
private String id;
private String plate;
private Instant registrationDate;
private String brand;
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleMapper is:
#Mapper(componentModel = "spring")
public interface VehicleMapper{
Vehicle toEntity(VehicleDTO source);
VehicleDTO toDto(Vehicle target);
}
The VehicleResource is:
#RestController
#RequestMapping("/api")
#CrossOrigin(origins = "*", methods = { RequestMethod.GET, RequestMethod.POST })
public class VehicleResource {
private final Logger log = LoggerFactory.getLogger(VehicleResource.class);
#Value("${jhipster.clientApp.name}")
private String applicationName;
#Autowired
private final VehicleService vehicleService;
public VehicleResource(VehicleService vehicleService) {
this.vehicleService = vehicleService;
}
#PostMapping("/vehicle")
#PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Vehicle> createVehicle(#Valid #RequestBody VehicleDTO vehicleDTO) throws URISyntaxException {
log.debug("REST request to save Vehicle : {}", vehicleDTO);
Vehicle newVehicle = vehicleService.createVehicle(vehicleDTO);
return ResponseEntity.created(new URI("/api/vehicle/" + newVehicle.getPlate()))
.headers(HeaderUtil.createAlert(applicationName, "vehicleManagement.created", newVehicle.getPlate()))
.body(newVehicle);
}
}
The VehicleService interface is:
public interface VehicleService {
Vehicle createVehicle(VehicleDTO vehicleDTO);
}
The VehicleServiceImpl is:
#Service
public class VehicleServiceImpl implements VehicleService{
#Autowired
private final VehicleRepository vehicleRepository;
#Autowired
private final VehicleMapper mapper;
public VehicleServiceImpl(VehicleRepository vehicleRepository, VehicleMapper mapper) {
this.vehicleRepository = vehicleRepository;
this.mapper = mapper;
}
private final Logger log = LoggerFactory.getLogger(VehicleServiceImpl.class);
#Override
public Vehicle createVehicle(VehicleDTO vehicleDTO) {
Vehicle vehicle = vehicleRepository.save(mapper.toEntity(vehicleDTO));
log.debug("Created Information for vehicle: {}", vehicle);
return vehicle;
}
}
The VehicleRepository interface is:
/**
* Spring Data MongoDB repository for the {#link Vehicle} entity.
*/
#Repository
public interface VehicleRepository extends MongoRepository<Vehicle, String> {
}
From the Swagger console I access the Vehicle-Resource:
Swagger console
Click on the button and write in the text box the json with the vehicle data:
enter JSON data
As we can see in the following image, the answer is 201. Initially the vehicle was saved with the identifier "id": "60e740935ed5a10e2c2ed19e".
Send request
I access the database to check that the vehicle has been correctly stored in the vehicle table. To my surprise ... there is no vehicle in the vehicle table:
show database
I can make sure that the data in the database application-dev is OK. I don't have any other databases.
I suspect that transactions with the database are not actually being made. This data is somehow stored in memory because if I do a findAllVehicles from Swagger it does return the vehicle.
I have a eureka server running (jhipster-registry) and two microservices that synchronize with it. The Gateway, which acts as a reverse proxy and the Vehiculos microservice. The Swagger console is the gateway, from where I make the request to insert vehicles. Everything seems to work, but as I say in bbdd does not save anything.

Assertion error for testing Junit with reactive WebTestClient Status Expected :201 Actual :404

#ExtendWith(SpringExtension.class)
#WebFluxTest(controllers = EventsControllerTest.class)
class EventsControllerTest {
#MockBean
UserRepo repo;
#Autowired
private WebTestClient webClient;
#Test
void testAssignUserRoles() {
UserInfo user = new UserInfo();
user.setId(Long.valueOf(1));
user.setFirstname("Test");
user.setLastname("Test2");
user.setActiveuser(true);
user.setEmailid("tet#test.com");
user.setRolename("test");
user.setUserpassword("test");
Mockito.when(repo.save(user)).thenReturn(Mono.just(user));
webClient.post().uri("/assignRoles").contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(user)).exchange().expectStatus().isCreated();
Mockito.verify(repo, times(1)).save(user);
}
Controller
#RestController
public class EventsController {
#Autowired
UserInfoRepository userInfoRepository;
#PostMapping(value = "/saveRole")
public Mono<UserInfo> assignUserRoles(#RequestBody UserInfo userInfo) {
return userInfoRepository.save(userInfo).log();
}
Access URI should match value attribute of #PostMapping: saveRole.

Spring Security + PostgreSql - How to debug whats going wrong with authentication since there are no error messages?

I am following Spring in action book and creating a small demo application to enhance my spring knowledge.
When i tried to setup spring security with PostgreSQL and tried to test authenticated requests, I am always getting 403 forbidden error with no error messages in console log.
I would like to understand whats wrong with the code.
I tried to add debug level for security, introduced AuthenticationEventListener to monitor the events etc. But none of them tell me why authentication fails.
Register controller working fine and its saving user details to DB with encoded password.
For complete code please look into https://github.com/vin0010/Spring-Recipe
SecurityConfig.java
#Configuration
#EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
//TODO check why it didn't work
#Autowired
#Qualifier("name")
private UserDetailsService userDetailsService;
#Value("${spring.queries.users-query}")
private String usersQuery;
#Value("${spring.queries.roles-query}")
private String rolesQuery;
#Autowired
public BCryptPasswordEncoder passwordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/test").authenticated()
.antMatchers("/register", "/**").permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.and()
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(passwordEncoder);
}
}
TestController for authentication check
#RestController
#RequestMapping("test")
public class TestController {
#GetMapping
public String getDocument(){
return "success";
}
}
Registration controller
#RequestMapping("/register")
public class RegistrationController {
#Autowired
private UserRepository userRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.ACCEPTED)
public void send(#RequestBody RegistrationForm registrationForm) {
userRepository.save(registrationForm.toUser(passwordEncoder));
}
}
UserRepository.java
public interface UserRepository extends CrudRepository<Users, Long> {
Users findByUsername(String username);
}
UserRepositoryUserDetailsService.java
#Service("name")
public class UserRepositoryUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Users users= userRepository.findByUsername(userName);
if (users == null)
throw new UsernameNotFoundException("User '" + userName + "' not found");
return users;
}
}
Users.java
#Entity
#Data
#NoArgsConstructor(access= AccessLevel.PRIVATE, force=true)
#RequiredArgsConstructor
public class Users implements UserDetails {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private final String username;
private final String password;
private final boolean enabled;
private final String role;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Arrays.asList(new SimpleGrantedAuthority(this.role));
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return this.enabled;
}
}
queries for user authentication and authorities check
spring.queries.users-query=select username, password, enabled from users where username=?
spring.queries.roles-query=select username, role from users where username=?
Since I created my own User table, I need to get the authentication done via this en entity setup.