将Spring配置为使用数据库进行身份验证 [英] Configure Spring to use Database for authentication

查看:207
本文介绍了将Spring配置为使用数据库进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想配置Spring Security以将数据库用于Rest api请求.我试过了:

I want to configure Spring Security to use database for Rest api requests. I tried this:

    @Configuration
    @EnableWebSecurity
    @Import(value= {Application.class, ContextDatasource.class})
    @ComponentScan(basePackages= {"org.rest.api.server.*"})
    public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired 
        private RestAuthEntryPoint authenticationEntryPoint;

        @Autowired
        MyUserDetailsService myUserDetailsService;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    //      auth
    //      .inMemoryAuthentication()
    //      .withUser("test")
    //      .password(passwordEncoder().encode("testpwd"))
    //      .authorities("ROLE_USER");
            auth.userDetailsService(myUserDetailsService);
            auth.authenticationProvider(authenticationProvider());
        }
        @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
            authenticationProvider.setUserDetailsService(myUserDetailsService);
            authenticationProvider.setPasswordEncoder(passwordEncoder());
            return authenticationProvider;
        }
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
            .antMatchers("/securityNone")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint);
        }
        @Bean
        public PasswordEncoder passwordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
    }

服务:

    public interface MerchantsService {

        public Merchants getCredentials(String login, String pwd) throws Exception;
    }

服务实施

@Service
@Qualifier("merchantsService")
@Transactional
public class MerchantsServiceImpl implements MerchantsService {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Merchants getCredentials(String login, String pwd) throws Exception {
        String hql = "select e from " + Merchants.class.getName() + " e where e.login = ? and e.pwd = ?";

        Query query = entityManager.createQuery(hql).setParameter(0, login).setParameter(1, pwd);
        Merchants merchants = (Merchants) query.getSingleResult();

        return merchants;
    }
}



    @Service
    public class MyUserDetailsService implements UserDetailsService {

        @Autowired
        private MerchantsService merchantsService;

        @Override
        public Merchants loadUserByUsername(String username) {
            Merchants user = merchantsService.getCredentials(username, pwd);
            if (user == null) {
                throw new UsernameNotFoundException(username);
            }
            return user;
        }
    }

我有2个问题:

  1. 我如何使用Merchant对象,但是Spring接受Object UserDetails.我如何实现此功能?

  1. How I can use the Merchant object but Spring accepts Object UserDetails. How I can implement this functionality?

我如何使用用户名和密码对请求进行身份验证.我看到public UserDetails loadUserByUsername(String username)只能接受用户名.还有其他实现代码的方法吗?

How I can authenticate requests with username and password. I see that public UserDetails loadUserByUsername(String username) can accept only username. Is there other way to implement the code?

推荐答案

使用Spring Security时,必须实现一个服务,该服务实现 UserDetailsS​​ervice 和返回UserDetails的相应loadUserByUsername方法.这是一个示例方法:

When you use Spring Security you have to implement a service that implements the UserDetailsService and th corresponding loadUserByUsername method that returns UserDetails. Here is a sample method:

@Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = this.getUserByUsername(username); // getting the user from the database with our own method
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
  }

您不必担心对密码进行身份验证,因为Spring Security可以提供密码.

You dont have to worry about authenticating the password because spring security will tak of it.

这篇关于将Spring配置为使用数据库进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆