Confusion with Spring Security Based Authentication with mongo db Support

Im trying to log in the user to a web page where credentials are stored in mongodb. I used spring boot and did not know about spring security features.

This is why I ended up using the following controller code that works.

@RequestMapping("/auth")
String auth(@ModelAttribute("credential") Credential credential) throws AuthenticationFailedException {
    handler.authenticateUser(credential);
    log.debug("user: " + credential.getUsername() + " authenticated successfully via /auth");
    return "main";
}

handler:

@Autowired
private UserRepository repository;

public boolean authenticateUser(Credential credential) throws AuthenticationFailedException {        
    User authenticatedUser = repository.findByCredentialUsername(credential.getUsername());

    if (authenticatedUser == null)
        throw new AuthenticationFailedException(
                "cant find any user with name: " + credential.getUsername());

    boolean matches = EncryptionUtils.matchEncryptedPassword(credential.getPassword(),
            authenticatedUser);

    if (!matches)
        throw new AuthenticationFailedException(
                "provided password is not matching password stored in database");

    return matches;
}

Realizing that these servlet filters, etc. relatively easy to configure with spring-security, I changed my code, so I ended up with this.

Config:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  UserAuthenticationService userAuthService;

  @Bean
  public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userAuthService);
    provider.setPasswordEncoder(new BCryptPasswordEncoder());
    return provider;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.userDetailsService(userAuthService).authorizeRequests()
            .antMatchers("/register", "/", "/css/**", "/images/**", "/js/**", "/login")
            .permitAll().anyRequest().authenticated().and().
            formLogin().loginPage("/").and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();

  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
  }

SecurityWebInit:

public class SecurityWebInit extends AbstractSecurityWebApplicationInitializer {
  public SecurityWebInit() {
    super(SecurityConfig.class);
  }
}

UserAuthenticationService:

@Component
public class UserAuthenticationService implements UserDetailsService {
  private static final Logger log = Logger.getLogger(UserAuthenticationService.class);
  @Autowired
  private UserRepository repository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = repository.findByCredentialUsername(username);
        log.debug("called user auth service..");
        if (user == null)
            throw new UsernameNotFoundException("username :"+username+" not found.");
        else {
            AuthenticatedUser authUser = new AuthenticatedUser(user);
            return authUser;
        }
  }
}

AuthenticatedUser - model:

public class AuthenticatedUser implements UserDetails {  
  private User user; // user is my own model, not of spring-framework
  private static final Logger log = Logger.getLogger(AuthenticatedUser.class);

  public AuthenticatedUser(User user) {
      this.user = user;
  }
  .. //rest of interface impl. (any method returns true)

  //no roles or authorities modeled, yet
  @Override 
  public Collection<? extends GrantedAuthority> getAuthorities() {
      return null;
  }

modified controller:

@RequestMapping(method=RequestMethod.POST, value="/login")
String auth2(@RequestParam("username") String username, @RequestParam("password") String password) throws AuthenticationFailedException {
    Credential cred = new Credential();
    cred.setUsername(username);
    cred.setPassword(password);        
    handler.authenticateUser(cred);
    log.debug("user: " + cred.getUsername() + " authenticated successfully via /login");
    return "main";
}

Template:

<form method="post" action="/login" th:object="${credential}">
    <div class="form-group">
     <input type="email" th:field="*{username}" class="form-control"
      id="username" placeholder="Username/Email" />
    </div>
    <div class="form-group">
     <input type="password" th:field="*{password}"
      class="form-control" id="password" placeholder="Password" />
    </div>
    <button type="submit" class="btn btn-default login-button">Submit</button>
</form>

. , . , , localhost:8080/<anyRestrictedUrl>, - . log.debug(..) UserAuthenticationService, . , \login, , - spring ?!

, - / , db. , spring, .

@edit ( pom.xml):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
    <relativePath />
</parent>

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-crypto</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-core</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
 </dependency>

@update (, ):

1) : ( )

 http.userDetailsService(userAuthService).authorizeRequests()
            .antMatchers("/register", "/", "/css/**", "/images/**", "/js/**", "/login")
            .permitAll().anyRequest().authenticated().and().
            formLogin().loginPage("/").and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().csrf().disable();

2), @Override @Autowired annotation ( SO - ):

 @Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
}
+4
2

. , ! usernameParameter(..), passwordParameter(..) config(HttpSecurity http), . , , . :

formLogin().loginPage("/")
       .loginProcessingUrl("/login")
       .failureUrl("/")
       .defaultSuccessUrl("/main")
       .usernameParameter("username") //needed, if custom login page
       .passwordParameter("password") //needed, if custom login page

UserDetailsService .

, .

+2

SessionCreationPolicy IF_REQUIRED ALWAYS. " ", , SecurityContext.

0

Source: https://habr.com/ru/post/1650404/


All Articles