Reputation: 12081
I want to open up spring security to "the world" during development. jHipster has a amazing generator but I am a little confused. How can I open spring security for restful calls with no issue?
/**
* Authenticate a user from the database.
*/
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin,
user.getPassword(),
grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
}
}
Upvotes: 1
Views: 749
Reputation: 6352
To permit anyone to access the REST API, change the following line in your SecurityConfiguration.java, located at src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java
.antMatchers("/api/**").authenticated()
to
.antMatchers("/api/**").permitAll()
You can then restrict specific API endpoints if you want with either of the following annotations:
@Secured(AuthoritiesConstants.ADMIN)
or
@PreAuthorize("hasRole('ROLE_USER')")
Upvotes: 4