【问题标题】:Spring boot resource server principal nameSpring Boot 资源服务器主体名称
【发布时间】:2022-04-12 23:01:29
【问题描述】:

我有一个 Keycloak 服务器正在运行。以及作为资源服务器的 Spring Boot 应用程序。我可以进行身份​​验证并获取令牌,并且 Spring Boot 应用程序将接受该令牌。但是当我想从校长那里获取用户名时,我会得到一个 UUID 而不是我的电子邮件或用户名。我还在我的 keycloak 中添加了一个映射器,将首选用户名映射到用户名。它正在工作。

JWT 信息

  ...
  "scope": "openid profile email",
  "email_verified": true,
  "username": "test@test.com",
  "DOB": "12345",
  "name": "test test",
  "preferred_username": "test@test.com",
  "given_name": "test",
  "family_name": "test",
  "email": "test@test.com"
}

我的 Spring 应用属性:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/auth/realms/test

【问题讨论】:

  • 你是怎么拿到校长的?
  • @dreamcrash 我有一个简单的带有 get 方法的 Rest 控制器。 @GetMapping("/") @PreAuthorize("hasAnyRole('USER')") private Principal me(Principal principal){}

标签: java spring spring-boot oauth keycloak


【解决方案1】:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class JWTSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests(authz -> authz
            .anyRequest().permitAll().permitAll())
          .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}

【讨论】:

  • 你能删除 .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);从您的代码中提取并使用我提供的代码进行测试
  • 我收到此错误:没有 'org.springframework.security.oauth2.jwt.JwtDecoder' 类型的合格 bean 可用
  • 没关系你已经解决了你的问题吧?
  • @dreamcrash 为您提供帮助
  • 您是如何解决 No qualifying bean JwtDecoder 的问题的?得到同样的错误,。
【解决方案2】:

Spring Security 将 JWT 令牌作为主体保存到 SecurityContextHolder。例如,以下代码将返回您要查找的用户名。

...
import org.springframework.security.oauth2.jwt.Jwt;
...
@GetMapping(value = "current-user", produces = "application/json")
    ResponseEntity<String> getLoggedInUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Jwt principal = (Jwt) authentication.getPrincipal(); 
        String currentUserName = principal.getClaimAsString("username");
        return new ResponseEntity<String>(currentUserName, HttpStatus.OK);
    }

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2021-02-07
    • 2020-04-10
    • 1970-01-01
    • 2019-04-05
    • 2018-08-29
    • 2015-05-14
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多