在没有用户角色的情况下实现 Spring 安全性



我想在没有用户角色的情况下实现 Spring 安全性。我试过这个:

我想将 Spring 安全性配置为将数据库用于 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 安全性与用户角色一起使用?

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

因为Spring Security是关于身份验证和授权的。您希望自己进行身份验证,也不需要该角色。那为什么你使用Spring Security。Spring 安全性为您提供了进行身份验证和授权的最佳方式,因此应使用它。由于您已经实现了UserDetailsService.Spring 安全本身使用配置的 Bean 进行密码验证PasswordEncoder

相关内容

最新更新