【问题标题】:Spring Security + REST + postgreSQLSpring Security + REST + postgreSQL
【发布时间】:2017-12-18 07:01:57
【问题描述】:

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

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

【问题讨论】:

  • 你应该创建自己的 userdetailservice

标签: spring security spring-security


【解决方案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;
    }
}

【讨论】:

    【解决方案2】:

    你需要像这样为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 路线。

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 2019-08-16
      • 2015-05-04
      • 2013-10-08
      • 2013-03-15
      • 2014-08-31
      • 2014-11-02
      • 2014-03-25
      • 2016-04-22
      相关资源
      最近更新 更多