简体   繁体   English

Spring 引导资源服务器主体名称

[英]Spring boot resource server principal name

I have a Keycloak server running.我有一个 Keycloak 服务器在运行。 and a spring boot application as a resource server.和一个 spring 启动应用程序作为资源服务器。 I can authenticate and get token and the spring boot app will accept the token.我可以进行身份验证并获取令牌,spring 启动应用程序将接受令牌。 but when I want to get the username from the Principal I will get a UUID instead of my email or username.但是当我想从委托人那里获取用户名时,我会得到一个 UUID 而不是我的 email 或用户名。 I also added a mapper to my keycloak that maps preferred_username to username.我还在我的密钥斗篷中添加了一个映射器,将 preferred_username 映射到用户名。 and it's working.它正在工作。

JWT info 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"
}

my spring app properties:我的 spring 应用程序属性:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/auth/realms/test
@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);
    }
}

Spring Security saves the JWT token as principal to the SecurityContextHolder. Spring 安全将 JWT 令牌作为主体保存到 SecurityContextHolder。 For example the following code would return the username that you are looking for.例如,以下代码将返回您要查找的用户名。

...
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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM