Spring security UserDetails and controller (get user) - java

There is UserDetail and LoginController.
UserDetail gets the user from the database.
UserDetail
public class UserDetail implements UserDetailsService {
private final
UserServiceJpa userServiceJpa;
public UserDetail(UserServiceJpa userServiceJpa) {
this.userServiceJpa = userServiceJpa;
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// Get user
User user = userServiceJpa.findUserByEmail(email);
if (user == null){
throw new UsernameNotFoundException("There is no such user " + email);
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),
user.getEnabled(),
user.getAccount_non_expired(),
user.getCredentials_non_expired(),
user.getAccount_non_locked(),
getAuthorities());
}
private Collection<? extends GrantedAuthority> getAuthorities(){
List<SimpleGrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return authList;
}
}
LoginController
#Controller
public class LoginController {
#GetMapping(value = "/login")
public String login () {
return "/login";
}
}
Question! How in LoginController get this user, which was received by UserDetail?
I do this in order not to reconnect to the database. Thus, I want to know how the user was blocked if he was blocked - enabled, accountNonExpired, credentialsNonExpired, accountNonLocked

You can create a UserDetails class from your LoginController by Autowiring it, and then call the function in your login class.
#Controller
public class LoginController {
#Autowired
private UserDetails userDetails;
#GetMapping(value = "/login")
public String login (#QueryParam("email")String email) {
userDetails.loadUserByUsername(email);
return "/login";
}
}

Related

403 Forbidden page Spring Security

I can't seem to find the 403 error problem, when I send a JSON request to register in Postman I get the 403 Forbidden error with no message.
Postman Screenshot
SecureConfig.Java
This is the configuration file.
#EnableWebSecurity
#AllArgsConstructor
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
#Bean(BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.csrf()
.disable()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
AuthConroller
This is the controller of the project to authenticate, when I sign up the new user was added to the database successfully, it sends afterwards a mail verification to the fake mail using Mailtrap " https://mailtrap.io " . But when I request to receive the authentication token and the username I receive the error.
#RestController
#AllArgsConstructor
#RequestMapping(value = "/api/auth", consumes = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {
private final AuthService authService;
#PostMapping("/signup")
public ResponseEntity<String> signup(#RequestBody RegisterRequest registerRequest ) {
authService.signup(registerRequest);
return new ResponseEntity<>("User's Registration was successful", HttpStatus.OK);
}
#GetMapping("accountVerification/{token}")
public ResponseEntity<String> verifyAccount(#PathVariable String token){
authService.verifyAccount(token);
return new ResponseEntity<>("Account created successfully", HttpStatus.OK);
}
#PostMapping("/")
public String login(#RequestBody LoginRequest loginRequest){
return authService.login(loginRequest);
}
}
AuthService
This is the autentication service.
#Service
#AllArgsConstructor
public class AuthService {
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
private final VerificationTokenRepository verificationTokenRepository;
private final MailService mailService;
private final AuthenticationManager authenticationManager;
private final JwtProvider jwtProvider;
public void signup(RegisterRequest registerRequest){
User user = new User();
user.setUsername(registerRequest.getUsername());
user.setEmail(registerRequest.getEmail());
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
user.setEnabled(false);
user.setCreated(Instant.now());
userRepository.save(user);
String token = generetedVerificationToken(user);
mailService.sendMail(new NotificationEmail("Please " +
"Activate Your Account", user.getEmail(), "Thanks " +
"for signing up. Click on the link below to go home: " +
"http://localhost:8080/api/auth/accountVerification/" + token));
}
private String generetedVerificationToken(User user){
String token = UUID.randomUUID().toString();
VerificationToken verificationToken = new VerificationToken();
verificationToken.setToken(token);
verificationToken.setUser(user);
verificationTokenRepository.save(verificationToken);
return token;
}
public void verifyAccount(String token) {
Optional<VerificationToken> verificationToken = verificationTokenRepository.findByToken(token);
fetchUserAndEnable(verificationToken.orElseThrow(() -> new SpringRedditException("Invalid Token")));
}
private void fetchUserAndEnable(VerificationToken verificationToken){
String username = verificationToken.getUser().getUsername();
Optional<org.springframework.security.core.userdetails.User> v = userRepository.findByUsername(username);
UserDetails user = userRepository.findByUsername(username).orElseThrow(() -> new SpringRedditException("User not found with name - " + username));
User s = (User) user;
s.setEnabled(true);
userRepository.save(s);
}
public String encodePassword(String password) { return passwordEncoder.encode(password);}
public String login(LoginRequest loginRequest){
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
return jwtProvider.generatedToken(authentication);
}
}
JwtProvider
This class is to generate the tokens for each user. I didn't use the JKS I've found in the tutoriel, because it provides an error.
#Service
public class JwtProvider {
// private KeyStore keyStore;
private Key key;
#PostConstruct
public void init() {
key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
}
public String generatedToken(Authentication authentication){
org.springframework.security.core.userdetails.User principal =
(org.springframework.security.core.userdetails.User) authentication.getPrincipal();
return Jwts.builder()
.setSubject(principal.getUsername())
.signWith(key)
.compact();
}
}
UserDetailsServiceImpl
Here goes the implementation that gives the user authority to connect :
#Service
#AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) {
Optional<User> userOptional = userRepository.findByUsername(username);
User user = userOptional.orElseThrow(() -> new UsernameNotFoundException("No such user" +
"with username : " + username));
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(), user.isEnabled(), true,
true, true,
getAuthorities("USER"));
}
private Collection<? extends GrantedAuthority> getAuthorities(String role){
return singletonList(new SimpleGrantedAuthority(role));
}
}
and last
AutheticationResponse
In the DTO file we have this class in order to receive the authenticatonToken and the username in postman as a JSON format.
#Data
#AllArgsConstructor
#NoArgsConstructor
public class AuthenticationResponse {
private String authenticationToken;
private String username;
}
After adding logging.level.org.springframework.security=DEBUG to application.properties file, I managed to see the reason this error appears in the below image.
Debug results Screenshot

class org.springframework.security.core.userdetails.User cannot be cast

I use SpringSecurity in my web-project. When I try to login with username and password, I have this error in my stacktrace :
class org.springframework.security.core.userdetails.User cannot be cast to class com.cesi.cuberil.service.JwtUser (org.springframework.security.core.userdetails.User and com.cesi.cuberil.service.JwtUser are in unnamed module of loader 'app')
at com.cesi.cuberil.controller.AuthController.login(AuthController.java:116) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.2.jar:5.3.2]
Below, I will put classes where I think the problem comes from.
Here my JwtUser.java :
package com.cesi.cuberil.service;
import com.cesi.cuberil.model.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
#Data
public class JwtUser implements UserDetails {
private final String username;
private final String password;
private final boolean enabled;
private final Collection<? extends GrantedAuthority> authorities;
private static final long serialVersionUID = 1L;
private User user;
public JwtUser(String username, String password, Boolean enabled, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.authorities = authorities;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
Here my AuthController.java :
#RestController
#RequestMapping("/api/v1/auth")
#AllArgsConstructor
public class AuthController {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
PasswordEncoder encoder;
#Autowired
JwtUtils jwtUtils;
#PostMapping("/login")
public ResponseEntity<?> login(#Valid #RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
JwtUser myUserDetails = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<String> roles = myUserDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt, myUserDetails.getUser().getUserId(), myUserDetails.getUsername(), myUserDetails.getUser().getEmail(), roles));
}
}
Here my UserDetailsServiceImpl.java :
#Service
#AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserRepository userRepository;
public User getByUsername(String username) {
return userRepository.findByUsername(username);
}
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("user not found");
} else {
List<GrantedAuthority> listAuthorities = new ArrayList<GrantedAuthority>();
listAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, listAuthorities);
}
}
}
For information, I use java 11 and the lastest version of Spring Boot.
The problem lies on the return statement of UserDetailsServiceImpl.loadUserByUsername(..). Of course you can not cast User to JwtUser object since they are completely different. You should return the object you created extending UserDetails, which in your case is JwtUser.
The following will solve it:
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("user not found");
} else {
List<GrantedAuthority> listAuthorities = new ArrayList<GrantedAuthority>();
listAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new JwtUser(username, user.getPassword(), true, listAuthorities); // NOTE here
}
}
I think you should return JwtUser instance instead of org.springframework.security.core.userdetails.User. Cause JwtUser already implements UserDetails interface.
Here's an sample.
a cast from one object to another is only possible if there exists a inheritance relationship between these two classes. In your case both classes implements the same interface but there is no inheritance relationship between the class org.springframework.security.core.userdetails.User and your JwtUser.
I think the problem here is a bad use of Spring Security. You are setting the the Authentication in the SecurityContextHolder, calling directly the AuthenticationManager and later calling even the Principal instead of the Authentication from the SecurityContextHolder. I recommend you to do it more in a Standard way, using LoginAuthentication and adding in the Spring Security configuration the successHandler() event, where you can write your own implementation that writes the JwtResponse in the response object.

Spring Security - auto login not working after registering user

In my Spring Boot MVC application I used Spring Security to provide authentication and users registration. Authentication and registration of users are working correctly, but after creating user account I want to login him automatically. While doing this I am receiving BadCredentialsException. This user with the same credentials normally is correctly login in with the login form. I appreciate any help from you. Below is my code:
Method from controller
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") User user, BindingResult result,
WebRequest request, Errors errors) {
User registeredUser = null;
if (result.hasErrors() == false) {
registeredUser = createUserAccount(user, result);
}
if (registeredUser == null) {
return "/register";
}
securityService.autologin(registeredUser.getLogin(), registeredUser.getPassword());
return "/whiprounds";
}
SecurityServiceImpl (method authenticate is throwing exception)
#Service
public class SecurityServiceImpl implements SecurityService {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserDetailsService userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);
#Override
public String findLoggedInLogin() {
Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
if (userDetails instanceof UserDetails) {
return ((UserDetails) userDetails).getUsername();
}
return null;
}
#Override
public void autologin(String username, String password) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
logger.debug(String.format("Auto login %s successfully!", username));
}
}
}
UserServiceImpl
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Autowired
private RoleRepository roleRepository;
#Override
public User registerNewUserAccount(User user) throws LoginExistsException {
if (loginExists(user.getLogin())) {
throw new LoginExistsException("User with this login already exists");
}
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>((Collection<? extends Role>) roleRepository.findAll()));
return userRepository.save(user);
}
private boolean loginExists(String login) {
User user = userRepository.findByLogin(login);
if (user != null) {
return true;
}
return false;
}
}
UserDetailsServiceImpl
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findByLogin(s);
if (user == null) {
throw new UsernameNotFoundException(s);
}
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
}
}
First of all, this method throwing an exception because of the password problem (As far as I can see from your code). Your method registerNewUserAccount returning User object which password has already been hashed. Then you passing it here:
securityService.autologin(registeredUser.getLogin(), registeredUser.getPassword());
So it turns out that you're passing hashed password into authenticationManager later. This is wrong - you should pass original password into it. Smth like this:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") User user, BindingResult result,
WebRequest request, Errors errors) {
User registeredUser = null;
String originalPassword = user.getPassword();
if (result.hasErrors() == false) {
registeredUser = createUserAccount(user, result);
}
if (registeredUser == null) {
return "/register";
}
securityService.autologin(registeredUser.getLogin(), originalPassword);
return "/whiprounds";
}
Second of all, authenticationManager.authenticate(usernamePasswordAuthenticationToken); - this method actually returns filled Authentication object (if authentication was successful), and you should put this object into SecurityContext, and not the one you've passed to `authenticationManager'. Smth like this:
#Override
public void autologin(String username, String password) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
Authentication auth = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (auth.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(auth);
logger.debug(String.format("Auto login %s successfully!", username));
}
}
Hope this helps.

Manually set Authenticated Spring User

I am building a SpringBoot application.
I am using Spring Security, and have a UserDetailsService implementation setup:
public class MyUserDetailService implements UserDetailsService {
#Autowired
private UserService userService;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User springUser = null;
User user = userService.loadUserByUsername(username);
if(user != null){
List<SimpleGrantedAuthority> authorities = null;
List<Role> roles = user.getRoles();
if(roles != null){
authorities = new ArrayList<>();
for(Role currentRole: roles){
authorities.add(new SimpleGrantedAuthority(currentRole.name()));
}
}
springUser = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
return springUser;
}
}
I have a service layer that contains method for adding users to the database:
public interface UserService {
public Long addStandardUser(String firstName, String lastName, String username, String password);
#PreAuthorize("hasRole('ADMIN')")
public Long addAdministratorUser(String firstName, String lastName, String username, String password);
#PreAuthorize("hasRole('ADMIN')")
public User loadUserByUsername(String username);
public Iterable<User> getUsers(int pageNumber, int pageSize, Direction direction, String sort);
}
I also have a CommandLineRunner implementation that I use (in dev mode) to initialize the database with sample users:
#Component
#Profile("dev")
public class DBInitializer implements CommandLineRunner {
#Autowired
private UserService userService;
#Override
public void run(String... args) throws Exception {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ADMIN"));
Authentication authentication = new UsernamePasswordAuthenticationToken("foo", null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
userService.addAdministratorUser("John", "Doe", "jdoe", "1234");
System.out.println("done!");
}
}
The trouble is that I am getting an Access Denied exception from Spring in the CommandLineRunner when I try to add the user. I'm assuming that the issue is that I am manually 'injecting' a Spring User incorrectly. The addAdminUser() method has to be run by a user in the ADMIN role, so I need to temporarily run as an ADMIN user. I know there is a #RunAs annotation that I remember using in other J2EE apps, but I'm not sure how that interfaces with a Spring application, or if that is used in a different context altogether
...
// The default role prefix starts with `ROLE_`
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
...
More detail please see here

Authentication with Spring Security + Spring data + MongoDB

I want to use Spring security with MongoDB (using Spring data) and retrieve the users from my own database for spring security. However, I can not do that since my userservice type does not seem to be supported.
This is my UserService class:
public class UserService {
private ApplicationContext applicationContext;
private MongoOperations mongoOperations;
public UserService() {
applicationContext = new AnnotationConfigApplicationContext(MongoConfig.class);
mongoOperations = (MongoOperations) applicationContext.getBean("mongoTemplate");
}
public User find(String username) {
return mongoOperations.findOne(Query.query(Criteria.where("username").is(username)), User.class);
}
}
And my SecurityConfig class:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserService userService;
#Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService); //THIS DOES NOT WORK
builder.inMemoryAuthentication().withUser("username").password("password").roles("USER");
}
}
The line I commented says:
The inferred type UserService is not a valid substitute for the bounded parameter <T extends UserDetailsService>.
How can I fix it so I can retrieve the users from my own database?
Service Layer
You have to create a separate service implementing org.springframework.security.core.userdetails.UserDetailsService and inject it inside the AuthenticationManagerBuilder.
#Component
public class SecUserDetailsService implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*Here add user data layer fetching from the MongoDB.
I have used userRepository*/
User user = userRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException(username);
}else{
UserDetails details = new SecUserDetails(user);
return details;
}
}
}
Model
UserDetails Should be also implemented. This is the POJO which will keep the user authenticated details by the Spring. You may include your Entity data object wrapped inside it, as I have done.
public class SecUserDetails implements UserDetails {
private User user;
public SecUserDetails(User user) {
this.user = user;
}
......
......
......
}
Security Config
Autowire the service that we created before and set it inside the AuthenticationManagerBuilder
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
SecUserDetailsService userDetailsService ;
#Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
}
Create your own authentication provider providing a class that extends the UserDetailservice.
Ensure content scanning is enable in your spring context xml file.
<authentication-provider user-service-ref="userModelService">
<password-encoder hash="sha" />
</authentication-provider>
#Service
public class UserModelService implements UserDetailsService
{
#Autowired
private UserModelRepositoryImpl repository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
UserModel user = repository.findByUsername(username);
if( user == null )
throw new UsernameNotFoundException( "Name not found!" );
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
return new User(user.getUsername(), user.getSHA1Password(), authorities );
}
public void saveUserDetails(UserModel userModel)
{
repository.save(userModel);
}
}
This class will enable spring query mongo for the username and password required for authentication. Next create the user model class.
public class UserModel
{
private String id;
#Indexed(unique=true)
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
Create the user implementation class that extends the DAO.
#Service
public class UserModelService implements UserDetailsService
{
#Autowired
private UserModelRepositoryImpl repository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
UserModel user = repository.findByUsername(username);
if( user == null )
throw new UsernameNotFoundException( "Oops!" );
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
return new User(user.getUsername(), user.getSHA1Password(), authorities );
}
Finally configure mongo and you're done.

Categories

Resources