【问题标题】:Spring Boot Security Authentication from third API来自第三个 API 的 Spring Boot 安全认证
【发布时间】:2020-05-10 09:46:55
【问题描述】:

我使用 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);
}}

任何人都可以帮助我, 提前致谢

最好的尊重

哈菲兹

【问题讨论】:

  • 我正在使用 AuthenticationProvider

标签: spring-boot spring-security thymeleaf


【解决方案1】:

一种方法是创建自己的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
         }
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 2018-09-07
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2018-05-19
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多