Spring Security + REST + postgreSQL

时间:2017-07-13 13:09:00

标签: spring security spring-security

我使用Spring Security编写了关于授权的教程https://auth0.com/blog/securing-spring-boot-with-jwts/,但此示例使用了硬编码的用户数据。我想授权使用数据库PostgreSQL。我怎样才能做到这一点?或者您是否知道使用Spring REST Security和PostgreSQL在github上的一些示例?

package com.example.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers(HttpMethod.POST, "/login").permitAll()
        .anyRequest().authenticated()
        .and()
        // We filter the api/login requests
        .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                UsernamePasswordAuthenticationFilter.class)
        // And filter other requests to check the presence of JWT in header
        .addFilterBefore(new JWTAuthenticationFilter(),
                UsernamePasswordAuthenticationFilter.class);
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // Create a default account
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("password")
        .roles("ADMIN");
  }
}

2 个答案:

答案 0 :(得分:1)

您需要像这样

为dataSource创建一个bean
@Bean
public DriverManagerDataSource dataSource() {
     DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
     driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
     driverManagerDataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/mydb");
     driverManagerDataSource.setUsername("postgres");
     driverManagerDataSource.setPassword("root");
     return driverManagerDataSource;
 }

然后在WebSecurityConfig类中自动装配javax.sql.DataSource

 @Autowired
 DataSource dataSource;

如果您的密码是Bcrypt编码,则为passwordEncoder创建一个bean

    @Bean(name="passwordEncoder")
    public PasswordEncoder passwordencoder(){
        return new BCryptPasswordEncoder();
    }

配置如下身份验证:

 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
   auth.jdbcAuthentication().dataSource(dataSource)
  .usersByUsernameQuery(
   "select email,password from users where email=?").passwordEncoder(passwordencoder());
 } 

最后点击/login路线。

答案 1 :(得分:1)

您可以将它与您的自定义userdetailservice一起使用,如下所示:

@Autowired
    private CustomUserDetailService userDetailsService;

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

并添加customuserdetail服务:

@Service
public class CustomUserDetailService implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        User user = getUserFromDatabase();

        UserItem userItem =  new UserItem(user.getUsername(),user.getPassword(),true,true,true,true, new ArrayList<GrantedAuthority>());;

        userItem.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER"));
        return userItem;
    }
}