java - 配置 Spring 以使用数据库进行身份验证
问题描述
我想将 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 Merchants loadUserByUsername(String username) {
Merchants user = merchantsService.getCredentials(username, pwd);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
我有两个问题:
我如何使用 Merchant 对象但 Spring 接受 Object UserDetails。我怎样才能实现这个功能?
如何使用用户名和密码验证请求。我看到
public UserDetails loadUserByUsername(String username)
只能接受用户名。还有其他方法可以实现代码吗?
解决方案
当您使用 Spring Security 时,您必须实现一个实现UserDetailsService的服务以及返回 UserDetails 的相应 loadUserByUsername 方法。这是一个示例方法:
@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 会处理它。
推荐阅读
- python - cv2 的自动完成功能在 vscode 中无法正常工作
- python - 用 PySpark 替换多个值
- arrays - 使用 XSLT 1.0 的数组
- configuration - ansible 基础设施即代码:从配置文件中创建、更新、删除用户
- java - 如何将 java 变量中的值作为回调传递给 Unity c# 变量或函数(通过 Android 插件)
- python - 为什么我的海龟绘图会根据我设置像素数量的方式产生不同的图片?
- wordpress - 如果标签与公司名称匹配,则显示自定义帖子类型
- twitter - Tweepy 30 天搜索中的不记名令牌放置
- microsoft-graph-api - /auditLogs/signIns 端点报告 我没有高级许可证
- javascript - Ajax XHR 加载失败,内部服务器错误 500