使用 mongo 支持的数据库与基于 Spring Security 的身份验证混淆

lun*_*ikz 5 java spring spring-security mongodb spring-boot

我正在尝试将用户登录到一个网页,其中凭据存储在 mongodb 中。我正在使用 spring boot 并且不知道 spring 安全功能。

这就是我最终使用以下控制器代码的原因,该代码有效:

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

处理程序:

@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;
}
Run Code Online (Sandbox Code Playgroud)

在意识到使用 spring-security 设置 servlet 过滤器等相对容易后,我更改了我的代码,所以我最终得到了这个:

配置:

@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());
  }
Run Code Online (Sandbox Code Playgroud)

安全网络初始化:

public class SecurityWebInit extends AbstractSecurityWebApplicationInitializer {
  public SecurityWebInit() {
    super(SecurityConfig.class);
  }
}
Run Code Online (Sandbox Code Playgroud)

用户身份验证服务:

@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;
        }
  }
}
Run Code Online (Sandbox Code Playgroud)

AuthenticatedUser - 型号:

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;
  }
Run Code Online (Sandbox Code Playgroud)

修改后的控制器:

@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";
}
Run Code Online (Sandbox Code Playgroud)

模板:

<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>
Run Code Online (Sandbox Code Playgroud)

提供的所有代码都更少地从另一个教程和示例中聚集在一起。当我通过基于表单的登录进行身份验证时,它确实有效。但是在我登录后,当我导航到localhost:8080/<anyRestrictedUrl>它时仍然将我重定向到登录表单。我也在log.debug(..)里面放了一些UserAuthenticationService,但我根本看不到任何一个..在大多数其他例子中,我什至看不到映射到的基本控制器方法\login,但我认为这是因为spring做了这个4我幕后?!

请注意,我没有使用任何权限和/或角色,因为它还没有在 db 中建模。在使用 spring security 时,这是必须的,因为大多数示例都包含角色和权限。

编辑:(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>
Run Code Online (Sandbox Code Playgroud)

更新:(我在上面提到的代码上尝试过的东西):

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();
Run Code Online (Sandbox Code Playgroud)

2) 用 @Autowired 注释替换 @Override(从另一个 SO 帖子中得到的 - 不工作):

@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
}
Run Code Online (Sandbox Code Playgroud)

lun*_*ikz 3

我可以解决这个问题..通过阅读这篇博客文章,事实证明,它是必要的!指定usernameParameter(..), passwordParameter(..)in config(HttpSecurity http),这与许多基本示例或教程中的做法不同。所以依赖默认值是我的遗憾。我必须附加:

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

如果没有这些参数设置,UserDetailsService则不会触发实现。

希望它对任何人都有帮助。