- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 442
 
switch to basic auth for API access #1545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 1 commit
      Commits
    
    
            Show all changes
          
          
            6 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      73de913
              
                switch to basic auth for API access
              
              
                goekay 9b2e1fa
              
                PR feedback
              
              
                goekay e646b47
              
                add cache for API users
              
              
                goekay e91bb34
              
                PR feedback
              
              
                goekay a729332
              
                start setting/updating api_password
              
              
                goekay d9dde45
              
                refactor: undo moveApiTokenFromConfigToDatabase prep
              
              
                goekay File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| 
          
            
          
           | 
    @@ -20,6 +20,8 @@ | |
| 
     | 
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.google.common.base.Strings; | ||
| import com.google.common.cache.Cache; | ||
| import com.google.common.cache.CacheBuilder; | ||
| import de.rwth.idsg.steve.service.WebUserService; | ||
| import de.rwth.idsg.steve.web.api.ApiControllerAdvice; | ||
| import lombok.RequiredArgsConstructor; | ||
| 
        
          
        
         | 
    @@ -32,6 +34,7 @@ | |
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.core.userdetails.User; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
| 
        
          
        
         | 
    @@ -42,6 +45,9 @@ | |
| import jakarta.servlet.http.HttpServletResponse; | ||
| 
     | 
||
| import java.io.IOException; | ||
| import java.util.Collections; | ||
| import java.util.concurrent.ExecutionException; | ||
| import java.util.concurrent.TimeUnit; | ||
| 
     | 
||
| /** | ||
| * @author Sevket Goekay <[email protected]> | ||
| 
        
          
        
         | 
    @@ -52,10 +58,18 @@ | |
| @RequiredArgsConstructor | ||
| public class ApiAuthenticationManager implements AuthenticationManager, AuthenticationEntryPoint { | ||
| 
     | 
||
| // Because Guava's cache does not accept a null value | ||
| private static final UserDetails DUMMY_USER = new User("#", "#", Collections.emptyList()); | ||
| 
     | 
||
| private final WebUserService webUserService; | ||
| private final PasswordEncoder passwordEncoder; | ||
| private final ObjectMapper jacksonObjectMapper; | ||
| 
     | 
||
| private final Cache<String, UserDetails> userCache = CacheBuilder.newBuilder() | ||
| .expireAfterWrite(10, TimeUnit.MINUTES) // TTL | ||
| .maximumSize(100) | ||
| .build(); | ||
| 
     | 
||
| @Override | ||
| public Authentication authenticate(Authentication authentication) throws AuthenticationException { | ||
| String username = (String) authentication.getPrincipal(); | ||
| 
        
          
        
         | 
    @@ -65,7 +79,7 @@ public Authentication authenticate(Authentication authentication) throws Authent | |
| throw new BadCredentialsException("Required parameters missing"); | ||
| } | ||
| 
     | 
||
| UserDetails userDetails = webUserService.loadUserByUsernameForApi(username); | ||
| UserDetails userDetails = getFromCacheOrDatabase(username); | ||
| if (!areValuesSet(userDetails)) { | ||
| throw new DisabledException("The user does not exist, exists but is disabled or has API access disabled."); | ||
| } | ||
| 
          
            
          
           | 
    @@ -99,8 +113,19 @@ public void commence(HttpServletRequest request, | |
| response.getWriter().print(jacksonObjectMapper.writeValueAsString(apiResponse)); | ||
| } | ||
| 
     | 
||
| private UserDetails getFromCacheOrDatabase(String username) { | ||
| try { | ||
| return userCache.get(username, () -> { | ||
| UserDetails user = webUserService.loadUserByUsernameForApi(username); | ||
| return (user == null) ? DUMMY_USER : user; | ||
| }); | ||
| } catch (ExecutionException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| 
     | 
||
| private static boolean areValuesSet(UserDetails userDetails) { | ||
| if (userDetails == null) { | ||
| if (userDetails == null || userDetails == DUMMY_USER) { | ||
| return false; | ||
| } | ||
| if (!userDetails.isEnabled()) { | ||
| 
          
            
          
           | 
    ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do you set the cache logic here instead of
webUserService.loadUserByUsernameForApi?I don't know if it is a choice to not use it but Spring has its own way of doing caches: https://spring.io/guides/gs/caching
And you can still use guava under to wood if you want it: https://docs.spring.io/spring-framework/docs/4.2.x/javadoc-api/org/springframework/cache/guava/GuavaCacheManager.html
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@goekay Just for my technical knowledge because I didn't use them before: why do you use guava directly and not hidden behind spring cache?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a combination of multiple reasons actually (disclaimer: i have been using both of them for a long time)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the answer! 👍
That could be true for almost every spring import ;)