java - 使用Spring Security中的PasswordEncoder

标签 java spring spring-mvc spring-security

我想在我的应用程序中使用 Spring Security 的 PasswordEnconder,但我在 Google 中找到的几乎所有文档和博客都通过在 SecurityConfig 类的 configureGlobal 方法中使用 .userDetailsS​​ervice() 来教授此过程。

在我的应用程序中,我有一个自定义的 AuthenticationProvider,它使用了 AuthenticationService(如下所列)。任何人都可以指出如何修改我的代码以包含对此资源的支持吗?

安全配置

@Configuration
@ComponentScan(value="com.spring.webapp.lojavirtual")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(authenticationProvider);
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/erro/login").permitAll()
                .antMatchers("/bootstrap/**", "/jquery/**", "/extra/**", "/publico/**", "/erro/publico/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/acesso/login").permitAll()
                .loginProcessingUrl("/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .successHandler(new CustomAuthenticationSuccessHandler())
                .failureHandler(new CustomAuthenticationFailureHandler())
                .and()
            .rememberMe()
                .key("lembrete")
                .useSecureCookie(true)
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/acesso/login").permitAll();
    }

}

自定义身份验证提供程序

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private AuthenticationService usuario;

    public CustomAuthenticationProvider() {
        super();
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails user = usuario.loadUserByUsername(name);

        if(user.getPassword().equals(password)) {
            Authentication auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
            return auth;
        }
        else {
            return null;
        }
    }

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

}

身份验证服务

@Service
public class AuthenticationService implements UserDetailsService {

    @Autowired
    private UsuarioHome accountDao;

    @Override
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Usuario account = accountDao.findByField("login", username);

        if(account==null) {
            System.out.println("No such user: " + username);
            throw new UsernameNotFoundException("No such user: " + username);
        } else if (account.getAutorizacao().isEmpty()) {
            System.out.println("User " + username + " has no authorities");
            throw new UsernameNotFoundException("User " + username + " has no authorities");
        }

        List<Permission> lista = new ArrayList<Permission>();
        int max = account.getAutorizacao().size();
        for(int i=0; i<max; i++) {
            for(int j=0; j<max; j++) {
                lista.add(account.getAutorizacao().get(i).getPermissao().get(j));
            }
        }

        boolean accountIsEnabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new User(account.getLogin(), account.getSenha(), accountIsEnabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(lista));
    }

    public List<String> getRolesAsList(List<Permission> list) {
        List <String> rolesAsList = new ArrayList<String>();
        for(Permission role : list){
            rolesAsList.add(role.getNome());
        }
        return rolesAsList;
    }

    public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(List<Permission> list) {
        List<GrantedAuthority> authList = getGrantedAuthorities(getRolesAsList(list));
        return authList;
    }

}

最佳答案

应该很简单。替换这个:

user.getPassword().equals(password)

有了这个

encoder.matches(password, user.getPassword())

关于java - 使用Spring Security中的PasswordEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23096350/

相关文章:

java - 如何获取 ParameterMap 中的键值列表(Spring)

java - 如何为 Spring MVC Controller 创建通用权限管理系统?

java - Spring Restful支持json数据多语言

spring - Spring 已弃用的 NoSuchRequestHandlingMethodException 的替代品是什么?

java - PackProtocolException : invalid advertisement when using the jgitflow-maven-plugin withing a jenkins job

java - HashMap返回方法

java - 将gzip添加到spring嵌入式tomcat中

java - 当我到处使用 Spring 时,是否值得拥有一个静态 Builder 类

java - Wicket 口 ModalWindow 错误

java - 响应式 JDK 8 中的 if/else