在没有用户角色的情况下实现Spring Security

时间:2018-09-08 09:04:20

标签: java spring spring-security spring-security-oauth2 spring-security-rest

我想在没有用户角色的情况下实现Spring Security。我尝试过:

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

    @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 UserDetails loadUserByUsername(String username) {
 Merchants user = merchantsService.getCredentials(username, pwd);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
}

        }

我有2个问题:

  1. 如何通过用户角色使用Spring Security?

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

1 个答案:

答案 0 :(得分:0)

Spring Security的全部功能都是关于身份验证和授权。您想自己进行身份验证,也不需要角色。那为什么要使用Spring Security呢? Spring Security为您提供了进行身份验证和授权的最佳方法,因此应使用它。由于您已经实现了UserDetailsService。 Spring Security本身使用配置的PasswordEncoder bean进行密码验证。