spring cloud oauth2 jwt 使用示例


spring cloud oauth2 jwt 使用示例

*****************************

认证服务器:authorization-server

*******************

配置文件

spring:
  application:
    name: authorization-server
server:
  port: 8081

*******************

config 层

JwtTokenStoreConfig:jwtTokenStore配置

@Configuration
public class JwtTokenStoreConfig {

    @Bean
    public JwtAccessTokenConverter initJwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("sign123456");

        return jwtAccessTokenConverter;
    }

    @Bean
    public JwtTokenStore initJwtTokenStore(){
        return new JwtTokenStore(initJwtAccessTokenConverter());
    }
}

OAuth2ServerConfig:认证服务器配置

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Resource
    private JwtTokenStore jwtTokenStore;

    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
        authorizationServerEndpointsConfigurer
                .tokenStore(jwtTokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("user")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("authorization_code","refresh_token")
                .redirectUris("http://localhost:8082/redirect")
                .accessTokenValiditySeconds(3000)
                .autoApprove(true)
                .scopes("user");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")    //获取token
                .checkTokenAccess("isAuthenticated()"); //验证token
    }
}

*****************************

资源服务器:resource-server

*******************

配置文件

spring:
  application:
    name: resource-server
server:
  port: 8082

security:
  oauth2:
    client:
      client-id: user
      client-secret: 123456
      user-authorization-uri: http://localhost:8081/oauth/authorize
      access-token-uri: http://localhost:8081/oauth/token
    resource:
      jwt:
        key-uri: http://localhost:8081/oauth/token_key
        key-value: sign123456

*******************

config 层

JwtTokenStoreConfig:jwtTokenStore配置

@Configuration
public class JwtTokenStoreConfig {

    @Bean
    public JwtAccessTokenConverter initJwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("sign123456");

        return jwtAccessTokenConverter;
    }

    @Bean
    public JwtTokenStore initJwtTokenStore(){
        return new JwtTokenStore(initJwtAccessTokenConverter());
    }
}

OAuth2ResourceServerConfig:资源服务器配置

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    private JwtTokenStore jwtTokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(jwtTokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/hello").hasAuthority("admin")
                .antMatchers("/redirect").permitAll();
    }
}

*******************

controller 层

@RestController
public class HelloController {

    @Value("${security.oauth2.client.access-token-uri}")
    private String accessTokenUri;

    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }

    @RequestMapping("/redirect") //获取授权码时的回调地址,使用获得的授权码获取access_token
    public Map get(@RequestParam(value = "code") String code){
        OkHttpClient httpClient=new OkHttpClient();

        RequestBody requestBody=new FormBody.Builder()
                .add("grant_type","authorization_code")
                .add("client","user")
                .add("redirect_uri","http://localhost:8082/redirect")
                .add("code",code)
                .build();

        Request request=new Request.Builder()
                .url(accessTokenUri)
                .post(requestBody)
                .addHeader("Authorization","Basic dXNlcjoxMjM0NTY=")
                .build();

        Map result=null;

        try {
            Response response=httpClient.newCall(request).execute();
            System.out.println(response);

            ObjectMapper objectMapper=new ObjectMapper();
            result=objectMapper.readValue(Objects.requireNonNull(response.body()).string(),Map.class);

            System.out.println("access_token:"+result.get("access_token"));
            System.out.println("token_type:"+result.get("token_type"));
            System.out.println("refresh_token:"+result.get("refresh_token"));
            System.out.println("expires_in:"+result.get("expires_in"));
            System.out.println("scope:"+result.get("scope"));
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return result;
    }
}

*****************************

使用测试

*******************

获取token

localhost:8081/oauth/aithorize

查询参数:client_id=user&response_type=code&redirect_uri=http://localhost:8082/redirect

         

解码token

              

*******************

获取后端数据

localhost:8082/hello,header设置为

key:Authorization

value:bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODEwODIwMzcsInVzZXJfbmFtZSI6Imd0bHgiLCJhdXRob3JpdGllcyI6WyJhZG1pbiJdLCJqdGkiOiI5NWE0NDEwNS01MTkxLTQ5NzktYTg1My0zMzVjZGM0MGUwNjIiLCJjbGllbnRfaWQiOiJ1c2VyIiwic2NvcGUiOlsidXNlciJdfQ.p2WUqo_bQU5faiBSe1CwWbCDMEdBVYzxcxPVb3U96ps

           

发布了337 篇原创文章 · 获赞 92 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/104206133