Spring Security OAuth2結(jié)合Jwt實(shí)現(xiàn)權(quán)限控制和安全保護(hù)

2020/09/02更新

Github開源腳手架运准,在網(wǎng)關(guān)處統(tǒng)一進(jìn)行鑒權(quán)憨降,授權(quán)服務(wù)器可單獨(dú)部署或者走網(wǎng)關(guān),具體見 https://github.com/beifei1/fire-cloud

本文基于Spring Cloud Security OAuth2實(shí)現(xiàn)微服務(wù)應(yīng)用的保護(hù),具體概念理解可參考

深入理解Spring Cloud Security OAuth2及JWT

應(yīng)用版本

Spring Boot: 2.1.1.RELEASE

Spring Cloud:Greenwich.SR2

應(yīng)用實(shí)現(xiàn)

Eureka Server服務(wù)

pom.xml

<?xml version="1.0" encoding="utf-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion> 
  <parent> 
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId>  
    <version>2.1.1.RELEASE</version>  
    <relativePath/>  
    <!-- lookup parent from repository --> 
  </parent>  
  <groupId>com.wang</groupId>  
  <artifactId>eureka-server</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>eureka-server</name>  
  <description>Demo project for Spring Boot</description>  
  <properties> 
    <java.version>1.8</java.version>  
    <spring-cloud.version>Greenwich.SR2</spring-cloud.version> 
  </properties>  
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.cloud</groupId>  
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>com.netflix.feign</groupId>  
      <artifactId>feign-slf4j</artifactId>  
      <version>8.14.4</version> 
    </dependency>  
    <dependency> 
      <groupId>org.projectlombok</groupId>  
      <artifactId>lombok</artifactId>  
      <optional>true</optional> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-test</artifactId>  
      <scope>test</scope>  
      <exclusions> 
        <exclusion> 
          <groupId>org.junit.vintage</groupId>  
          <artifactId>junit-vintage-engine</artifactId> 
        </exclusion> 
      </exclusions> 
    </dependency> 
  </dependencies>  
  <dependencyManagement> 
    <dependencies> 
      <dependency> 
        <groupId>org.springframework.cloud</groupId>  
        <artifactId>spring-cloud-dependencies</artifactId>  
        <version>${spring-cloud.version}</version>  
        <type>pom</type>  
        <scope>import</scope> 
      </dependency> 
    </dependencies> 
  </dependencyManagement>  
  <build> 
    <plugins> 
      <plugin> 
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
    </plugins> 
  </build> 
</project>

定義應(yīng)用配置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 #是否向注冊自己,該應(yīng)用為服務(wù)治理吏奸,不注冊自己
    fetch-registry: false #服務(wù)治理應(yīng)用,不拉取注冊列表

  server:
    enable-self-preservation: false #禁用自我保護(hù)
    eviction-interval-timer-in-ms: 5000 #剔除無用節(jié)點(diǎn)的間隔時(shí)間

定義啟動(dòng)類

@EnableEurekaServer //開啟eureka支持
@SpringBootApplication
public class EurekaServerApplication {

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

}

Auth Server服務(wù)

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) //啟用方法級權(quán)限控制
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))  //切入點(diǎn)陶耍,可自定義未授權(quán)響應(yīng)體

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在內(nèi)存中創(chuàng)建兩個(gè)用戶便于測試奋蔚,實(shí)際應(yīng)用可用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 //開啟授權(quán)服務(wù)器支持
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {

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

@Autowired
private JwtTokenEnhancer jwtTokenEnhancer; //自定義JWT內(nèi)容(jwt增強(qiáng)器)

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //定義兩個(gè)client,授權(quán)范圍為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增強(qiáng)鏈
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();

    List<TokenEnhancer> list = new ArrayList<>();
    list.add(jwtTokenEnhancer); //注入定義好的自定義token增強(qiáng)
    list.add(jwtAccessTokenConverter());

    tokenEnhancerChain.setTokenEnhancers(list);

    return tokenEnhancerChain;
}

}

定義JWT增強(qiáng)烈钞,可自由定義jwt的 拓展信息

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

}

關(guān)于JKS文件及pubkey相關(guān)使用可參考Java keytool生成jks證書泊碑,并使用openssl查看公鑰信息

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

user consumer(Resource Server)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wang</groupId>
    <artifactId>user-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>user-consumer</name>
    <description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

application.yml

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

啟動(dòng)類

@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();

        //使用命令查看上節(jié)中生成的jks中的pubkey內(nèi)容,并復(fù)制到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);
        //不設(shè)置會(huì)出現(xiàn) cant convert jwt to JSON 錯(cuò)誤
        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();  //所有路徑均需要授權(quán)
    }

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

}

測試controller

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

    @RequestMapping("/info")
    @PreAuthorize("hasRole('ADMIN')")  //需要授權(quán)并且必須擁有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授權(quán)方式獲取accessToken馒过,header中需要帶有基礎(chǔ)basic認(rèn)證,對應(yīng)auth config中client配置的用戶仪媒,響應(yīng)結(jié)果中包含了自定義的jwt拓展沉桌,同時(shí)該拓展項(xiàng)存在于jwt的payload中


圖片.png

使用accessToken訪問資源服務(wù)器中受保護(hù)的應(yīng)用


圖片.png

使用錯(cuò)誤的token訪問受保護(hù)資源谢鹊,響應(yīng)401錯(cuò)誤


圖片.png

使用權(quán)限不足的(沒有admin角色的token訪問需要admin權(quán)限的資源)算吩,響應(yīng)403


圖片.png

如果需要自定義錯(cuò)誤響應(yīng)內(nèi)容,可參考
Security OAuth2自定義異常響應(yīng)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末佃扼,一起剝皮案震驚了整個(gè)濱河市偎巢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌兼耀,老刑警劉巖压昼,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異瘤运,居然都是意外死亡窍霞,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進(jìn)店門拯坟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來但金,“玉大人,你說我怎么就攤上這事郁季±淅#” “怎么了?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵梦裂,是天一觀的道長似枕。 經(jīng)常有香客問我,道長年柠,這世上最難降的妖魔是什么凿歼? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上答憔,老公的妹妹穿的比我還像新娘牵咙。我一直安慰自己,他們只是感情好攀唯,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布洁桌。 她就那樣靜靜地躺著,像睡著了一般侯嘀。 火紅的嫁衣襯著肌膚如雪另凌。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天戒幔,我揣著相機(jī)與錄音吠谢,去河邊找鬼。 笑死诗茎,一個(gè)胖子當(dāng)著我的面吹牛工坊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播敢订,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼王污,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了楚午?” 一聲冷哼從身側(cè)響起昭齐,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎矾柜,沒想到半個(gè)月后阱驾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡怪蔑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年里覆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缆瓣。...
    茶點(diǎn)故事閱讀 38,724評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡喧枷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出捆愁,到底是詐尸還是另有隱情割去,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布昼丑,位于F島的核電站呻逆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏菩帝。R本人自食惡果不足惜咖城,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一茬腿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧宜雀,春花似錦切平、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至简烘,卻和暖如春苔严,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背孤澎。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工届氢, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人覆旭。 一個(gè)月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓退子,卻偏偏與公主長得像,于是被迫代替她去往敵國和親型将。 傳聞我的和親對象是個(gè)殘疾皇子寂祥,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評論 2 350