OAuth2簡易實戰(三)-JWT


1. OAuth2簡易實戰(三)-JWT

1.1. 與OAuth2授權碼模式差別

  1. 授權服務器代碼修改
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

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

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

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .authenticationManager(authenticationManager)
            .tokenStore(jwtTokenStore())
            .accessTokenConverter(accessTokenConverter());
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("clientapp")
            .secret("112233")
            .scopes("read_userinfo")
            .authorizedGrantTypes(
                "password",
                "authorization_code",
                "refresh_token");
    }

}
  1. 可以看到主要是增加了 JwtAccessTokenConverter JWT訪問令牌轉換器和JwtTokenStore JWT令牌存儲組件,通過AuthorizationServerEndpointsConfigurer 授權服務器端點配置加入兩個實例

1.2. 操作步驟

  1. 使用password模式,訪問以下鏈接,獲得token,記得加上授權賬戶密碼
http://localhost:8080/oauth/token?password=xyz&grant_type=password&username=bobo&scope=read_userinfo

  1. 返回值
  2. 使用access_token調用,成功

1.3. JWT的特殊性

  1. 可以看到代碼改動其實不大,jwt具有自解釋的特性,客戶端不需要再去授權服務器認證這個token的合法性
  2. 代碼中可以看到我們添加了一個簽名秘鑰test-secret,這個秘鑰需要自己保管好
  3. 通過訪問 https://jwt.io 把我試驗中返回的access_token加入,填上簽名秘鑰,可以看到驗證成功


4. 可以看出來,通過token的解碼,參數中帶有請求的一些信息,我們通過解碼可以直接獲取


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM