java - Auth0 API + Spring : How to verify user identity from successful Auth0 API response

标签 java spring spring-boot jwt auth0

问题

我正在尝试创建一个应用程序,该应用程序在前端使用 Auth0 SPA + React 来对用户进行身份验证,而无需处理密码。然后,我想保护我使用 Auth 服务器创建的任何端点,我需要使用 Spring Framework 创建。

澄清一下,流程是

Frontend ->
Auth through Auth0 ->
Redirect to users dashboard on frontend ->
Make HTTP request to endpoint sending JWT returned from Auth0 ->
Endpoint makes request to my Auth Server sending JWT returned from Auth0 ->
Auth server either either returns 401 or user object based on JWT ->
Endpoint grabs data specific to that user from DB ->
Returns data to frontend

我已经使用 Auth0 提供的快速入门指南 使我的前端正常工作,但我在弄清楚如何获取时遇到了很多麻烦我的Auth Service 来验证用户。

我相信我已经得出结论,我需要在 Auth0 上创建一个“API”并获取一个访问 token ,然后使用它来验证 JWT,在本例中它只是访问 token ,而不是我的前端包含的 JWT。我也让这部分工作,但似乎没有办法知道用户是谁。测试此“API”时,发送有效请求后我返回

{
  "iss": "https://${username}.auth0.com/",
  "sub": "${alphanumericCharacters}@clients",
  "aud": "${ApiIdentifier}",
  "iat": ${issuedAt},
  "exp": ${expiresAt},
  "azp": "${alphanumericCharacters}",
  "gty": "client-credentials"
}

虽然很高兴知道我走在正确的轨道上,但我似乎无法弄清楚如何处理此响应来找到用户。

预计

我希望在从我的Auth Service

验证access_token 后能够识别特定用户

代码

我没有太多代码可以展示,但我会通过我的Auth Service

提供我能提供的代码

安全配置.java

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${auth0.audience}")
    private String audience;

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuer;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .mvcMatchers("/api/validate")
                    .authenticated()
                .and()
                .oauth2ResourceServer()
                    .jwt();
    }

    @Bean
    JwtDecoder jwtDecoder() {
        NimbusJwtDecoderJwkSupport jwtDecoder = (NimbusJwtDecoderJwkSupport)
                JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }

}

受众 validator .java

public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
    private final String audience;

    public AudienceValidator(String audience) {
        this.audience = audience;
    }

    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);

        if (jwt.getAudience().contains(audience)) {
            return OAuth2TokenValidatorResult.success();
        }
        return OAuth2TokenValidatorResult.failure(error);
    }
}

验证 Controller .java

@RestController
@RequestMapping("/api/validate")
public class ValidateController {

    @GetMapping
    public boolean validate() {
        return true;  // only returns if successfully authed
    }

}

最佳答案

阅读文档后,我找到了解决方案。

事实证明,我不需要在 Auth0 上创建“API”,而是需要使用我的 Applications 端点( s) 来自Auth0Auth0 提供了许多基于您的帐户的端点,您可以从您的任何应用程序(CLI、服务器、客户端等)中尽可能利用这些端点:

  • 发出 HTTP 请求
  • 提供凭据

所以获取用户信息的方式是explained here .

数据流

使用我的项目身份验证/数据流,它几乎是:

  • 使用 @auth0/auth0-spa-js在前端,您可以在成功验证后使用 getTokenSilently() method 获取用户的access token .

  • 向您的休息服务

    发送 HTTP 请求
  • Rest Service 将该 token 发送到您的Auth Service

  • Auth Service 使用 Authorization 向 https://myAuth0Username.auth0.com/userinfo 发送 GET 请求:不记名 ${access_token} header 。 Example

  • 如果从 Auth0

    成功验证
    • 返回您的用户信息,例如“姓名”、“电子邮件”等。
  • 否则

    • 返回 403 禁止访问的 HTTP 状态
  • Auth Service 然后将 user object 返回给 Rest Service

  • Rest Service 然后为该端点执行必要的逻辑(数据库查询、另一个 HTTP 请求等)

验证 token 并返回用户的示例 Auth 服务端点

ValidateController.java

package x.SpringTodo_Auth.Controllers;

import x.SpringTodo_Auth.Models.User;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/validate")
public class ValidateController {

    @GetMapping
    public Object validate() {
        // Create and set the "Authorization" header before sending HTTP request
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + access_token);
        HttpEntity<String> entity = new HttpEntity<>("headers", headers);

        // Use the "RestTemplate" API provided by Spring to make the HTTP request
        RestTemplate restTemplate = new RestTemplate();
        Object user = restTemplate.exchange("https://myAuth0Username.auth0.com/userinfo", HttpMethod.POST, entity, User.class);
        return user;
    }

}

User.java(这是作为最后一个参数传递给 restTemplate.exchange(...) 方法的类

package x.SpringTodo_Auth.Models;

public class User {

    private String sub;
    private String given_name;
    private String family_name;
    private String nickname;
    private String name;
    private String picture;
    private String locale;
    private String updated_at;
    private String email;
    private boolean email_verified;

    // Getters/setters (or you can use Lombok)
}

关于java - Auth0 API + Spring : How to verify user identity from successful Auth0 API response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045340/

相关文章:

java - 在java中解析来自webservice的json数据

java - 为什么在新日期的代码中使用linethrough

javascript - 客户应该如何与服务交互?

java - 为什么 try catch 中的 return 语句与 'throws' 一起工作

Spring HATEOAS RepresentationModelAssembler toCollectionModel()

java - 使用 Maven 和 Spring 控制项目 : How to set Spring config file using Maven profiles?

java - 为什么我在关系字段中得到空值?

java - Spring MVC 与 AspectJ

java - 如何将声明推送到 keycloak?

spring-boot - 如何:使用外部配置文件构建Gradle Spring Boot应用