首页 > 解决方案 > 来自第三个 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);
}}

任何人帮助我,提前谢谢

最良好的问候

哈菲兹

标签: spring-bootspring-securitythymeleaf

解决方案


一种方法是创建自己的AuthenticationManagerbean,并将身份验证调用委托给第 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
         }
    }
}

推荐阅读