首页 > 解决方案 > Spring Security 自定义登录功能

问题描述

我正在开发 Vaadin/Spring 应用程序。对于登录,建议使用 Spring Security。按照文档 [1],我设置了 spring 安全性。现在我InMemoryUserDetailsManager在应用程序中使用硬编码的用户名/密码。

@Bean
@Override
public UserDetailsService userDetailsService() {
    UserDetails user =
            User.withUsername("user")
                    .password("{noop}pass")
                    .roles("USER")
                    .build();

    return new InMemoryUserDetailsManager(user);
}

一切都适用于此设置,但是对于日志记录,我调用了一个外部函数,该函数返回一个带有提供的用户名/密码对的布尔值,并且没有内置管理器允许这样做。

canLogin(user,pass);

这反过来又调用了一个外部服务。如何设置弹簧安全性以允许这样做?

[1] https://vaadin.com/learn/tutorials/modern-web-apps-with-spring-boot-and-vaadin/adding-a-login-screen-to-a-vaadin-app-with-spring -安全

标签: javaspringspring-securityvaadin

解决方案


Baeldung 文章Spring Security Authentication Provider有一个我认为适合您需求的示例。

只需创建您自己的身份验证提供程序,按照您认为合适的方式进行身份验证,然后将其注册到您的安全配置中。

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyAuthenticationService myAuthenticationService;

    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {
 
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        
        if (myAuthenticationService.canLogin(name, password)) {
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

推荐阅读