使用Spring Security的PasswordEncoder

克莱伯·莫塔(Kleber Mota)

我想在我的应用程序中使用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();
    }

}

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

}

认证服务

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

}
戴夫·赛尔(Dave Syer)

应该很简单。替换为:

user.getPassword().equals(password)

有了这个

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章