spring-boot - 来自第三个 API 的 Spring Boot 安全认证
问题描述
我使用 spring boot + thymeleaf 构建了一个 web 应用程序,但是这个项目是客户端(不是后端/不使用数据库),我正在使用第三个 API(登录、存储数据、加载数据、更新数据、删除数据),我有一个使用第三个 API 实现 Spring Boot 安全性、用户名和密码身份验证时出现问题,此端点用于登录身份验证(第三个 API)
http://kuala/app/directory/user/login?j_username=admin&j_password=admin
成功响应
{
"isAdmin": "true",
"username": "admin"}
响应失败
{
"error": {
"date": "Fri Jan 24 10:29:26 ICT 2020",
"code": "401",
"message": ""
}}
此示例 SecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/admin/**").hasAuthority("ADMIN")
.antMatchers("/user/**").hasAuthority("USER")
.anyRequest()
.authenticated().and().csrf().disable().formLogin()
.loginPage("/login").failureUrl("/login?error=true")
.defaultSuccessUrl("/home")
.usernameParameter("username")
.passwordParameter("password")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(appUserDetailsService);
}}
任何人帮助我,提前谢谢
最良好的问候
哈菲兹
解决方案
一种方法是创建自己的AuthenticationManager
bean,并将身份验证调用委托给第 3 方(例如,使用 RestTemplate):
@Component
public class CustomAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Call your 3rd party API and return an Authentication object based
// on its response
ResponseEntity loginResponse = restTemplate.exchange(...);
if(loginResponse.getStatusCode() == HttpStatus.OK) {
// create a valid Authentication object with roles, etc
}
else {
// throw an exception such as BadCredentialsException
}
}
}
推荐阅读
- nginx - 在 NGINX 后面时 Keycloak 无效的重定向 Uri
- excel - VBA如何根据现有列表检查重复值并仅从新列表中添加唯一实例
- json - 如何使用 sagemaker 将 s3 上的大型 json 文件读取到数据帧
- ios - iOS Firestore '文档路径不能为空'
- python - 给定一个密钥作为种子,如何对字节数组进行随机播放然后取消播放
- dictionary - 移动和拾取基于项目的游戏(可能的 if-else 语句问题)
- angular - 角度如何为现有项目创建一个csproj文件
- javascript - 将 Woocommerce 订单推送到 Google 表格
- c++ - 特征:围绕轴旋转矢量
- c# - 需要 C# 反射帮助