Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring boot安全编码密码轻松_Java_Spring_Security_Encryption - Fatal编程技术网

Java Spring boot安全编码密码轻松

Java Spring boot安全编码密码轻松,java,spring,security,encryption,Java,Spring,Security,Encryption,编辑: 我发现的最简单的方法是: @SuppressWarnings("deprecation") @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Autowired public void configAuthentication(

编辑:

我发现的最简单的方法是:

@SuppressWarnings("deprecation")
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
                "SELECT username, password, abilitazione FROM public.utenti WHERE username=?")
        .passwordEncoder(passwordEncoder())
        .authoritiesByUsernameQuery(
                "SELECT username, ruolo FROM public.ruoli_utente WHERE username=?");
    } 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //omitted for brevity
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
在我的dao类中,我添加了如下用户:

public void addElement(Utente u) {
    String password = u.getPassword();
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(password);
    u.setPassword(hashedPassword);
    jdbcTemplate.update("INSERT INTO public.utenti(username, password, abilitazione, email, nome, cognome) VALUES (?, ?, ?, ?, ?, ?)",
    new Object[] {u.getUsername(), u.getPassword(), u.getAbilitazione(), u.getEmail(), u.getNome(), u.getCognome()});

}
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
                "SELECT username, decode(password,'base64'), abilitazione FROM public.utenti WHERE username=?")
        .authoritiesByUsernameQuery(
                "SELECT username, ruolo FROM public.ruoli_utente WHERE username=?");
    } 
}

我想以一种超级简单的方式加密和解密密码,不管它是否超级安全,它只是为了我的目的必须是安全的。 所以,我在数据库中添加了加密密码。 当用户进行身份验证时,即使我对密码进行了解码,它也无法识别密码。我是这样做的:

public void addElement(Utente u) {
    String password = u.getPassword();
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(password);
    u.setPassword(hashedPassword);
    jdbcTemplate.update("INSERT INTO public.utenti(username, password, abilitazione, email, nome, cognome) VALUES (?, ?, ?, ?, ?, ?)",
    new Object[] {u.getUsername(), u.getPassword(), u.getAbilitazione(), u.getEmail(), u.getNome(), u.getCognome()});

}
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
                "SELECT username, decode(password,'base64'), abilitazione FROM public.utenti WHERE username=?")
        .authoritiesByUsernameQuery(
                "SELECT username, ruolo FROM public.ruoli_utente WHERE username=?");
    } 
}

它可以以类似的方式工作(直接在usersByUsernameQuery方法中解码),或者我必须声明一些bean进行解码?

我是这样做的,看起来非常干净,可以接受更改

在应用程序类中:

@Bean
public ApplicationSecurity applicationSecurity() {
    return new ApplicationSecurity();
}  
您的应用程序安全类

public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailSecurityService userDetailSecurityService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/ace/**",
                                                            "/app/**",
                                                            "/jquery/**",
                                                            "/bootstrap/**",
                                                            "/font-awesome/**",
                                                            "/jstree/**",
                                                            "/img/**").permitAll().anyRequest()
            .fullyAuthenticated();

        http.csrf().disable().formLogin().loginPage("/login").failureUrl("/login?error=1").permitAll().defaultSuccessUrl("/configurator").and().logout().permitAll();

        http.headers().frameOptions().disable().addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "SAMEORIGIN"));
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws  Exception {
        auth.userDetailsService(userDetailSecurityService).passwordEncoder(passwordEncoder());
    }


     @Bean
     public PasswordEncoder passwordEncoder(){
         return new MD5PasswordEncoder();
     }

}
以及类MDPasswordEncoder,或您想要使用的任何实现:

public class MD5PasswordEncoder implements PasswordEncoder {

     @Override
     public String encode(CharSequence charSequence) {
         String encPass = "";
        try {
             MessageDigest md = MessageDigest.getInstance("MD5");
             byte[] digest = md.digest(charSequence.toString().getBytes());
             byte[] b64 = Base64.encodeBase64(digest);
             encPass = new String(b64);
             encPass = encPass.replaceAll("=", "");
         }catch(Exception ex){
             logger.error("An exception trying to encode a password", ex);
         }
         return encPass;
     }

     @Override
     public boolean matches(CharSequence charSequence, String s) {
         return encode(charSequence).equals(s);
     }
}

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}


@Service
public class UserDetailSecurityService implements UserDetailsService{

    //Here your user service implementation
    @Autowired
    UserService userService;

    //yuou need to oeverride this method name
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // you need to create a method in your service to find users by name
        return userService.findByUsername(username);
    }
}

在这种情况下,如果您需要更改为一个新的编码器方法,您只需要使用适当的系统实现一个新类,就可以完成了

我就是这样做的,而且看起来非常干净,可以进行更改

在应用程序类中:

@Bean
public ApplicationSecurity applicationSecurity() {
    return new ApplicationSecurity();
}  
您的应用程序安全类

public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailSecurityService userDetailSecurityService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/ace/**",
                                                            "/app/**",
                                                            "/jquery/**",
                                                            "/bootstrap/**",
                                                            "/font-awesome/**",
                                                            "/jstree/**",
                                                            "/img/**").permitAll().anyRequest()
            .fullyAuthenticated();

        http.csrf().disable().formLogin().loginPage("/login").failureUrl("/login?error=1").permitAll().defaultSuccessUrl("/configurator").and().logout().permitAll();

        http.headers().frameOptions().disable().addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "SAMEORIGIN"));
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws  Exception {
        auth.userDetailsService(userDetailSecurityService).passwordEncoder(passwordEncoder());
    }


     @Bean
     public PasswordEncoder passwordEncoder(){
         return new MD5PasswordEncoder();
     }

}
以及类MDPasswordEncoder,或您想要使用的任何实现:

public class MD5PasswordEncoder implements PasswordEncoder {

     @Override
     public String encode(CharSequence charSequence) {
         String encPass = "";
        try {
             MessageDigest md = MessageDigest.getInstance("MD5");
             byte[] digest = md.digest(charSequence.toString().getBytes());
             byte[] b64 = Base64.encodeBase64(digest);
             encPass = new String(b64);
             encPass = encPass.replaceAll("=", "");
         }catch(Exception ex){
             logger.error("An exception trying to encode a password", ex);
         }
         return encPass;
     }

     @Override
     public boolean matches(CharSequence charSequence, String s) {
         return encode(charSequence).equals(s);
     }
}

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}


@Service
public class UserDetailSecurityService implements UserDetailsService{

    //Here your user service implementation
    @Autowired
    UserService userService;

    //yuou need to oeverride this method name
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // you need to create a method in your service to find users by name
        return userService.findByUsername(username);
    }
}

在这种情况下,如果您需要更改为新的编码器方法,您只需要使用适当的系统实现一个新类,就可以完成

您是如何实现类UserDetailSecurityService的?@tina添加了2个类我正在试图理解为什么我所做的不起作用。您编写了一个类userservice(它肯定使用一个userdao类),它执行configAuthentication方法在我的类中所做的操作。那么,如果我在我的sql中使用解码函数,为什么它在我的db中工作,而在项目中不工作呢?为什么您必须使用一种从sql查询中对密码进行编码和解码的方法?@tina通常sql没有相同的密码解码/编码选项,实际上我甚至不确定是否可能。这就是为什么需要在Java中添加解码器class@tina对我来说,如果你不混合使用DB和身份验证,就更容易了。例如,如果你想添加一些测试来验证你的解码系统是否工作,那么你的代码总是需要DB访问权限,所以不是孤立的。但是让我检查一下你的例子中可能有什么错误你是如何做你的类UserDetailSecurityService的?@tina添加了两个类我正在试图理解为什么我所做的不起作用。您编写了一个类userservice(它肯定使用一个userdao类),它执行configAuthentication方法在我的类中所做的操作。那么,如果我在我的sql中使用解码函数,为什么它在我的db中工作,而在项目中不工作呢?为什么您必须使用一种从sql查询中对密码进行编码和解码的方法?@tina通常sql没有相同的密码解码/编码选项,实际上我甚至不确定是否可能。这就是为什么需要在Java中添加解码器class@tina对我来说,如果你不混合使用DB和身份验证,就更容易了。例如,如果你想添加一些测试来验证你的解码系统是否工作,那么你的代码总是需要DB访问权限,所以不是孤立的。但让我检查一下你的例子中可能有什么错误