Spring Security OAuth2结合Jwt实现权限控制和安全保护

2020/09/02更新

Github开源脚手架,在网关处统一进行鉴权,授权服务器可单独部署或者走网关,具体见 https://github.com/beifei1/fire-cloud

本文基于Spring Cloud Security OAuth2实现微服务应用的保护,具体概念理解可参考

深入理解Spring Cloud Security OAuth2及JWT

应用版本

Spring Boot: 2.1.1.RELEASE

Spring Cloud:Greenwich.SR2

应用实现

Eureka Server服务

pom.xml



  
  4.0.0 
   
    org.springframework.boot  
    spring-boot-starter-parent  
    2.1.1.RELEASE  
      
     
    
  com.wang  
  eureka-server  
  0.0.1-SNAPSHOT  
  eureka-server  
  Demo project for Spring Boot  
   
    1.8  
    Greenwich.SR2 
    
   
     
      org.springframework.cloud  
      spring-cloud-starter-netflix-eureka-server 
      
     
      org.springframework.boot  
      spring-boot-starter-web 
      
     
      com.netflix.feign  
      feign-slf4j  
      8.14.4 
      
     
      org.projectlombok  
      lombok  
      true 
      
     
      org.springframework.boot  
      spring-boot-starter-test  
      test  
       
         
          org.junit.vintage  
          junit-vintage-engine 
         
       
     
    
   
     
       
        org.springframework.cloud  
        spring-cloud-dependencies  
        ${spring-cloud.version}  
        pom  
        import 
       
     
    
   
     
       
        org.springframework.boot  
        spring-boot-maven-plugin 
       
     
   

定义应用配置application.yml

spring:
  application:
    name: eureka-server #application name

eureka:
  instance:
    hostname: localhost
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
    register-with-eureka: false #是否向注册自己,该应用为服务治理,不注册自己
    fetch-registry: false #服务治理应用,不拉取注册列表

  server:
    enable-self-preservation: false #禁用自我保护
    eviction-interval-timer-in-ms: 5000 #剔除无用节点的间隔时间

定义启动类

@EnableEurekaServer //开启eureka支持
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

Auth Server服务

application.yml

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka

server:
  port: 8081

spring:
  application:
    name: auth-service
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/spring-cloud-auth?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&useSSL=false&serverTimezone=GMT
    username: root
    password: root123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

spring security安全配置

@Configuration
@EnableWebSecurity //启用security
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级权限控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request,response,exception) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))  //切入点,可自定义未授权响应体

                .and()
                .authorizeRequests()
                .antMatchers("/**").authenticated() //所有路径均启用安全
                .and().httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中创建两个用户便于测试,实际应用可用userdetail
        auth.inMemoryAuthentication()
                .withUser("wangzhichao").password("123456").roles("USER").and()            .withUser("admin").password("123456").roles("ADMIN").and().passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}

oauth2配置

@Configuration
@EnableAuthorizationServer //开启授权服务器支持
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;  //注入Security配置中的manager

@Autowired
private JwtTokenEnhancer jwtTokenEnhancer; //自定义JWT内容(jwt增强器)

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //定义两个client,授权范围为refresh_token,password
    clients.inMemory()
            .withClient("app").secret("123456").scopes("app-service").authorizedGrantTypes("refresh_token","password")
            .and()
            .withClient("system").secret("123456").scopes("system-service").authorizedGrantTypes("refresh_token","password")
            .accessTokenValiditySeconds(3600);
}

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

public TokenStore tokenStore() {
    return new JwtTokenStore(jwtAccessTokenConverter());
}

//jwt token 解析器
private JwtAccessTokenConverter jwtAccessTokenConverter() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("study-jwt.jks"),"123456".toCharArray());

    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("study-jwt"));

    return converter;
}

public TokenEnhancerChain initTokenEnhancerChanin() {
    //token增强链
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();

    List list = new ArrayList<>();
    list.add(jwtTokenEnhancer); //注入定义好的自定义token增强
    list.add(jwtAccessTokenConverter());

    tokenEnhancerChain.setTokenEnhancers(list);

    return tokenEnhancerChain;
}

}

定义JWT增强,可自由定义jwt的 拓展信息

@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessTokenoAuth2AccessToken,OAuth2Authentication oAuth2Authentication) {
        Map map = new HashMap<>();
        map.put("extension","jwt 拓展信息");
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);
    return oAuth2AccessToken;
    }

}

关于JKS文件及pubkey相关使用可参考Java keytool生成jks证书,并使用openssl查看公钥信息

把生成的jks文件放入到auth文件的classpath中

user consumer(Resource Server)

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
         
    
    com.wang
    user-consumer
    0.0.1-SNAPSHOT
    user-consumer
    Demo project for Spring Boot


    1.8
    Greenwich.SR2



    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
    
        org.springframework.boot
        spring-boot-starter-security
    
    
        org.springframework.cloud
        spring-cloud-starter-oauth2
    
    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.projectlombok
        lombok
        true
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
        
            
                org.junit.vintage
                junit-vintage-engine
            
        
    
    
        org.springframework.security
        spring-security-test
        test
    



    
        
            org.springframework.cloud
            spring-cloud-dependencies
            ${spring-cloud.version}
            pom
            import
        
    



    
        
            org.springframework.boot
            spring-boot-maven-plugin
        
    



application.yml

server:
  port: 8082
spring:
  application:
    name: user-consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/

启动类

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级安全配置
public class UserConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserConsumerApplication.class, args);
    }

}

配置jwt解析器

@Configuration
public class JwtConfig {

    @Bean
    @Qualifier("tokenStore")
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();

        //使用命令查看上节中生成的jks中的pubkey内容,并复制到public.pub文件中,粘贴到resource server的classpath中
        Resource resource = new ClassPathResource("public.pub");
        String pubkey = null;

        try {
            pubkey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        converter.setVerifierKey(pubkey);
        //不设置会出现 cant convert jwt to JSON 错误
        converter.setVerifier(new RsaVerifier(pubkey));

        return converter;
    }

}

resource server配置

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/**").authenticated();  //所有路径均需要授权
    }

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

}

测试controller

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/info")
    @PreAuthorize("hasRole('ADMIN')")  //需要授权并且必须拥有ADMIN角色
    public String userDetail(Authentication authentication) {
        log.info(authentication.getDetails().toString());
        return authentication.getPrincipal().toString();
    }
    
    @RequestMapping("/simple")
    public String hhhhh() {
        return "simple string";
    }

}

使用admin及密码采用password授权方式获取accessToken,header中需要带有基础basic认证,对应auth config中client配置的用户,响应结果中包含了自定义的jwt拓展,同时该拓展项存在于jwt的payload中


图片.png

使用accessToken访问资源服务器中受保护的应用


图片.png

使用错误的token访问受保护资源,响应401错误


图片.png

使用权限不足的(没有admin角色的token访问需要admin权限的资源),响应403


图片.png

如果需要自定义错误响应内容,可参考
Security OAuth2自定义异常响应

你可能感兴趣的:(Spring Security OAuth2结合Jwt实现权限控制和安全保护)