如何在Spring Boot中通过Auth0实现使用JWT注册和登录?

问题描述 投票:0回答:1

我有一个一直在使用 HTTP 基本身份验证的 Spring Boot REST API(Spring Boot 版本 3.0.4)。我现在开始使用 Auth0 进行 JWT 身份验证。到目前为止,我已经使用以下安全配置使用 Spring Boot 的 OAuth2 资源服务器配置了 JWT 身份验证:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration {


    public static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher("/users/**", "POST"),
            new AntPathRequestMatcher("/error/**")
    );


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .cors(Customizer.withDefaults())
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(PUBLIC_URLS).permitAll()
                        .anyRequest().authenticated())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

我已经使用我的 Auth0 仪表板创建了一个 API,并且还在我的 应用程序中添加了以下属性。属性

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://<my-domain-here>.us.auth0.com/
spring.security.oauth2.resourceserver.jwt.audiences=localhost:8000
auth0.audience=localhost:8000

我已遵循 Auth0 的本指南。该指南提到了如何保护端点,但不包含有关如何从客户端获取访问令牌或服务器将 Spring Boot API 中的用户与令牌相关联的注册或登录过程的任何信息。

我已经有一个

AppUsersController
用于注册和检索最初使用 HTTP 基本身份验证的当前用户:

@RestController
@RequestMapping(value = "users", produces = MediaType.APPLICATION_JSON_VALUE)
public class AppUsersController {

    private final AppUserRepository repository;
    private final PasswordEncoder encoder;

    public AppUsersController(AppUserRepository repository, PasswordEncoder encoder) {
        this.repository = repository;
        this.encoder = encoder;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public AppUserInfoDto register(@RequestBody @Valid AppUserRegistrationDto registration) {

        String username = registration.email();

        if (repository.findByUsername(username).isPresent()) {
            throw new UsernameAlreadyExistsException(username);
        }

        AppUser user = repository.save(registration.toUser(encoder));

        return AppUserInfoDto.fromAppUser(user);
    }


    @GetMapping
    public AppUserInfoDto current(@AuthenticationPrincipal User user) {
        return repository
                .findByUsername(user.getUsername())
                .map(AppUserInfoDto::fromAppUser)
                .orElseThrow(AppUserNotFoundException::new);
    }
}

问题是我发现的大多数指南都演示了使用自签名公私密钥对登录和注册以生成 JWT 令牌,每次用户登录时,都会使用

TokenService
手动创建令牌,然后使用
AuthenticationManager.authenticate()
。此外,还有像 this 这样的指南来使用模板引擎而不是 REST API 为 Web 应用程序设置登录。

有为 Angular 或 React 等客户端获取访问令牌的示例。但是,如果我想使用 curl 或 Postman 登录或注册怎么办? (我的客户端最初是一个 JavaFX 应用程序,它向我的 Spring Boot API 发出 HTTP 请求。)

我如何修改我的

AppUsersController
以支持使用配置的 JWT 身份验证和 Auth0 注册和登录?

这是我的

UserDetailsService

@Service
public class AppUserDetailsService implements UserDetailsService {

    private final AppUserRepository userRepository;

    public AppUserDetailsService(AppUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AppUser user = userRepository
                .findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("The username " + username + " was not found"));

        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(Collections.emptyList())
                .build();
    }
}

GitHub 上提供了应用程序源:

java spring-boot jwt spring-security-oauth2 auth0
1个回答
-3
投票

Spring Boot Version 3.0.4 不是处理 JWT 的稳定版本。

© www.soinside.com 2019 - 2024. All rights reserved.