简体   繁体   English

Oauth2 服务器返回“访问令牌”而不是 Jwt 令牌

[英]Oauth2 Server returns "Access Token" instead of Jwt Token

Following the tutorial that can be found here to replace existing oauth configuration that returns an 'access token' for aa jwt token.按照可以在此处找到的教程替换现有的 oauth 配置,该配置为 aa jwt 令牌返回“访问令牌”。 When I run the application and query the server for authentication, it seem to be returning an "access_token" instead of a JWT Token.当我运行应用程序并查询服务器进行身份验证时,它似乎返回“access_token”而不是 JWT 令牌。 The tutorial is using spring boot and our application is a non-boot plain spring mvc, therefore not sure if there is any additional steps involved?本教程使用的是 spring boot,我们的应用程序是非启动普通 spring mvc,因此不确定是否涉及任何其他步骤?

Server response: {"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ3aWxsbGFkaXNsYXciLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ2OGI3MzFmLTUxMzgtNDZhYi04MTU3LTU1MmZlMjM1MzY2ZSIsImNsaWVudF9pZCI6ImNsaWVudGFwcCIsInNjb3BlIjpbInJlYWRfd3JpdGUiXSwib3JnYW5pemF0aW9uIjoid2lsbGxhZGlzbGF3QmdNSiJ9.fUhFeUDuhm8f2V7CuURsZWKoAKjNZixk5rUa0Jyzov8","refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbsUiOiJ3aWxsbGFkaXNsYXciLCJzY29wZSI6WyJyZWFkX3dyaXRlIl0sIm9yZ2FuaXphdGlvbiI6IndpbGxsYWRpc2xhd0JnTUoiLCJhdGkiOiI0NjhiNzMxZi01MTM4LTQ2YWItODE1Ny01NTJmZTIzNTM2NmUiLCJleHAiOjE1ODM4NDA5NTgsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiOGIxNGE3NjMtZmMwMy00MDQ4LWJkNGQtYjZiMTUyOGU2NTE4IiwiY2xpZW50X2lkIjoiY2xpZW50YXBwIn0.UhkxVsgM4CnZeRRKGyyCbiyqb2M0BmL56sHbsxt5Opk","idToken":null,"tokenEndpoint":"http://localhost:8080/oauth/token","scopes":["read_write"],"expiration":null}服务器响应: {"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ3aWxsbGFkaXNsYXciLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ2OGI3MzFmLTUxMzgtNDZhYi04MTU3LTU1MmZlMjM1MzY2ZSIsImNsaWVudF9pZCI6ImNsaWVudGFwcCIsInNjb3BlIjpbInJlYWRfd3JpdGUiXSwib3JnYW5pemF0aW9uIjoid2lsbGxhZGlzbGF3QmdNSiJ9.fUhFeUDuhm8f2V7CuURsZWKoAKjNZixk5rUa0Jyzov8","refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbsUiOiJ3aWxsbGFkaXNsYXciLCJzY29wZSI6WyJyZWFkX3dyaXRlIl0sIm9yZ2FuaXphdGlvbiI6IndpbGxsYWRpc2xhd0JnTUoiLCJhdGkiOiI0NjhiNzMxZi01MTM4LTQ2YWItODE1Ny01NTJmZTIzNTM2NmUiLCJleHAiOjE1ODM4NDA5NTgsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiOGIxNGE3NjMtZmMwMy00MDQ4LWJkNGQtYjZiMTUyOGU2NTE4IiwiY2xpZW50X2lkIjoiY2xpZW50YXBwIn0.UhkxVsgM4CnZeRRKGyyCbiyqb2M0BmL56sHbsxt5Opk","idToken":null,"tokenEndpoint":"http://localhost:8080/oauth/token","scopes":["read_write"],"expiration":null}

//OAuth Server //OAuth服务器

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    final String clientId;
    final String clientSecret;
    final String redirectUri;
    final String grantType;
    final String scope;
  ....

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    DataSource dataSource;

    @Autowired
    RepositoryUserDetailsService userDetailsService;

    @Autowired
    private CustomAccessTokenConverter customAccessTokenConverter;


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(
                Arrays.asList(tokenEnhancer(), accessTokenConverter()));

        endpoints.tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123");
        return converter;
    }

    @Bean
    @Primary
    public ResourceServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }


    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }



    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.
                jdbc(dataSource)
                .withClient(clientId)
                .secret(passwordEncoder.encode(clientSecret))
                .autoApprove(true)
                .redirectUris(redirectUri)
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(0)
                .scopes(scope);
    }
}

//Resource Server //资源服务器

@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
    @Autowired
    private CustomAccessTokenConverter customAccessTokenConverter;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/register/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin().loginPage("/signin/**")
                .and()
                .requestMatchers()
                .antMatchers("/api/**");

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer config) {
        config.tokenServices(tokenServices());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setAccessTokenConverter(customAccessTokenConverter);
        converter.setSigningKey("123");
        return converter;
    }

    @Bean
    @Primary
    public ResourceServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

}

//CustomTokenEnhancer Class //CustomTokenEnhancer 类

public class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put(
                "organization", authentication.getName() + randomAlphabetic(4));
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(
                additionalInfo);
        return accessToken;
    }
}

//CustomAccessTokenConverter Class //CustomAccessTokenConverter 类

@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
        OAuth2Authentication authentication =
                super.extractAuthentication(claims);
        authentication.setDetails(claims);
        return authentication;
    }
}

Your Spring Security OAuth2 configuration works as it should be and is already returning a JWT token.您的 Spring Security OAuth2 配置按原样工作,并且已经返回 JWT 令牌。

Following is the payload it returns以下是它返回的有效载荷

eyJ1c2VyX25hbWUiOiJ3aWxsbGFkaXNsYXciLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ2OGI3MzFmLTUxMzgtNDZhYi04MTU3LTU1MmZlMjM1MzY2ZSIsImNsaWVudF9pZCI6ImNsaWVudGFwcCIsInNjb3BlIjpbInJlYWRfd3JpdGUiXSwib3JnYW5pemF0aW9uIjoid2lsbGxhZGlzbGF3QmdNSiJ9

This is what it looks like after decoding it with base64这是用base64解码后的样子

{"user_name":"willladislaw","authorities":["ROLE_ADMIN"],"jti":"468b731f-5138-46ab-8157-552fe235366e","client_id":"clientapp","scope":["read_write"],"organization":"willladislawBgMJ"}

You can now use the following JWT Token in the header value Authorization: Bearer <JWT Token> and access any protected resource.您现在可以在标头值Authorization: Bearer <JWT Token>使用以下 JWT 令牌并访问任何受保护的资源。

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ3aWxsbGFkaXNsYXciLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ2OGI3MzFmLTUxMzgtNDZhYi04MTU3LTU1MmZlMjM1MzY2ZSIsImNsaWVudF9pZCI6ImNsaWVudGFwcCIsInNjb3BlIjpbInJlYWRfd3JpdGUiXSwib3JnYW5pemF0aW9uIjoid2lsbGxhZGlzbGF3QmdNSiJ9.fUhFeUDuhm8f2V7CuURsZWKoAKjNZixk5rUa0Jyzov8

What you have done is you have asked Spring Security OAuth2 to generate a JWT Token with self contained information about the logged in user and replace that for the standard UUID based accessToken it uses by default.您所做的是要求 Spring Security OAuth2 生成一个 JWT 令牌,其中包含有关登录用户的自包含信息,并将其替换为它默认使用的基于标准 UUID 的accessToken Just because you are using JWT Token doesn't mean you will get a jwtToken return from oauth/token endpoint at login.仅仅因为您使用 JWT 令牌并不意味着您将在登录时从oauth/token端点获得 jwtToken 返回。 Learn more about JWT .了解有关JWT 的更多信息。

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

相关问题 带有加密 JWT 访问令牌的 Spring Boot OAuth2 - Spring Boot OAuth2 with encrypted JWT access token Spring Boot 2.0.4 + OAuth2 + JWT-无法获取访问令牌,返回405或仅被映射到localhost:8080 / - Spring Boot 2.0.4 + OAuth2 + JWT - Cannot get Access Token, returns 405 or just gets mapped into localhost:8080/ Spring Security OAuth2 JWT 匿名令牌 - Spring Security OAuth2 JWT anonymous token 撤销JWT Oauth2刷新令牌 - Revoke JWT Oauth2 Refresh Token Spring Webflux SecurityValidate OAuth2 JWT 令牌 - Spring Webflux SecurityValidate OAuth2 JWT Token 如何撤销用户作为管理员用户的访问令牌和刷新令牌? 在 Oauth2 中使用 JWT 时 - How to revoke the access token and refresh token of the user as an admin user? while using JWT in Oauth2 仅在 JWT 令牌中而不是在 OAuth2 令牌中添加附加信息 - Add additionnal information only in the JWT token and not in the OAuth2 token 如何以及在何处从 oauth2 授权服务器获取访问令牌? - How and where to get access token from oauth2 authorization server? 在 Spring 引导中成功 Oauth2 登录后 Cookie 身份验证而不是 JWT 承载令牌 - Cookie Authentication instead of JWT Bearer Token after a successful Oauth2 Login in Spring Boot 使用Spring Security OAuth2的JWT承载交换访问令牌请求 - JWT bearer exchange for access token request using Spring Security OAuth2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM