简体   繁体   English

Spring引导安全性REST基础认证来自数据库

[英]Spring boot security REST basic authentication from database

I have a problem where when I use basic authentication with inMemoryAuthentication as in the following snippet, it works perfectly. 我有一个问题,当我使用inMemoryAuthentication的基本身份验证时,如下面的代码片段,它完美地工作。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user1").password("secret1").roles("USER")
                .and()
                .withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
                .csrf().disable().headers().frameOptions().disable();
    }

}

but when I try to use get database to get userdata that will be used for authentication it doesn't work and just sends back a 403 response. 但是当我尝试使用get database来获取将用于身份验证的userdata时,它不起作用,只返回403响应。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;//MySQL db via JPA

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
                .authoritiesByUsernameQuery("select username, role from user where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
                .csrf().disable().headers().frameOptions().disable();

    }

}

now, this is the case only with a Spring-Boot REST application, I've tried the same method in a Spring MVC application and a /login page and it worked with both inMemoryAuthentication and jdbcAuthentication . 现在,只有Spring-Boot REST应用程序就是这种情况,我在Spring MVC应用程序和/ login页面中尝试了相同的方法,它同时适用inMemoryAuthenticationjdbcAuthentication

I had the same problem, in my case the following solution worked perfectly 我有同样的问题,在我的情况下,以下解决方案完美地工作

Create a class that implements AuthenticationProvider interface: 创建一个实现AuthenticationProvider接口的类:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userService.findUserByEmail(email);

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

        return new UsernamePasswordAuthenticationToken(email, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN) 在此处对用户进行身份验证,您使用您的用户服务通过电子邮件(用户名)从数据库中检索用户,并使用他的电子邮件,密码和他授予的权限创建令牌(例如:USER,ADMIN)

then in your SecurityConfig class use the the bean you have just created as follows: 然后在SecurityConfig类中使用刚刚创建的bean,如下所示:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
                .csrf().disable().headers().frameOptions().disable();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM