Thoy_N_A
(Thoy N/A)
January 14, 2024, 1:38pm
1
Hi guys i have a spring boot login and registration , when i run it in local with the following configs it woks perfectly! as shown in the image BUT if i change over to Mongo compass it does not work not can i find my database for my roles
spring.data.mongodb.database=bezkoder_db
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
# App Properties
bezkoder.app.jwtCookieName= bezkoder
bezkoder.app.jwtSecret=
bezkoder.app.jwtExpirationMs= 86400000
Mongo compass screenshot :
THIS IS THE CODE I AM USING FOR MONGO COMPASS :
@SpringBootApplication
public class SpringBootMongodbLoginApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMongodbLoginApplication.class, args);
String connectionString = "mongodb+srv://<username>:<password>@moodcraftai.uygfyac.mongodb.net/?retryWrites=true&w=majority";
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.serverApi(serverApi)
.build();
// Create a new client and connect to the server
try (MongoClient mongoClient = MongoClients.create(settings)) {
try {
// Send a ping to confirm a successful connection
MongoDatabase database = mongoClient.getDatabase("mongo");
database.runCommand(new Document("ping", 1));
System.out.println("Pinged your deployment. You successfully connected to MongoDB!");
} catch (MongoException e) {
e.printStackTrace();
}
}
}
}
Does anyone know why it will not work or find the collection?
Hey @Thoy_N_A ,
Welcome to the MongoDB Community forums
Could you confirm if you meant MongoDB Atlas ? To rephrase the question: it works fine with the MongoDB local deployment but not with MongoDB Atlas. Let me know if I understood it correctly.
In this context, MongoDB Compass is the GUI tool for interacting with your database cluster. You can use it to connect to both MongoDB Atlas and local deployments, allowing you to interact with the database and collection.
The code snippet you shared, I believe, contains the code for connecting to the MongoDB Atlas cluster. I don’t see any database operations happening in the provided code snippet. Could you please share the code snippet where you are inserting values into the “roles” collection?
Meanwhile, you can refer to the quick start repository - java-spring-boot-mongodb-starter to get started with Spring boot and MongoDB.
Best regards,
Kushagra
Thoy_N_A
(Thoy N/A)
February 17, 2024, 10:20pm
4
hi thank you for your reply yes you ate correct i am attempting to connect to my cloud database :
i am manually creating the
package com.bezkoder.spring.security.mongodb.controllers;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bezkoder.spring.security.mongodb.models.ERole;
import com.bezkoder.spring.security.mongodb.models.Role;
import com.bezkoder.spring.security.mongodb.models.User;
import com.bezkoder.spring.security.mongodb.payload.request.LoginRequest;
import com.bezkoder.spring.security.mongodb.payload.request.SignupRequest;
import com.bezkoder.spring.security.mongodb.payload.response.UserInfoResponse;
import com.bezkoder.spring.security.mongodb.payload.response.MessageResponse;
import com.bezkoder.spring.security.mongodb.repository.RoleRepository;
import com.bezkoder.spring.security.mongodb.repository.UserRepository;
import com.bezkoder.spring.security.mongodb.security.jwt.JwtUtils;
import com.bezkoder.spring.security.mongodb.security.services.UserDetailsImpl;
//for Angular Client (withCredentials)
//@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600, allowCredentials="true")
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(userDetails);
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
.body(new UserInfoResponse(userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRoles();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found.1"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found.2"));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found.3"));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found.4"));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
CODE FOR ROLE
package com.bezkoder.spring.security.mongodb.repository;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.bezkoder.spring.security.mongodb.models.ERole;
import com.bezkoder.spring.security.mongodb.models.Role;
public interface RoleRepository extends MongoRepository<Role, String> {
Optional<Role> findByName(ERole name);
}