使用Spring Security的PasswordEncoder

时间:2014-04-15 23:30:20

标签: java spring spring-mvc spring-security

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

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

SecurityConfig

@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();
    }

}

CustomAuthenticationProvider

@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);
    }

}

的AuthenticationService

@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;
    }

}

1 个答案:

答案 0 :(得分:2)

应该很简单。替换这个:

user.getPassword().equals(password)

用这个

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