3, 互聯(lián)網(wǎng)安全架構(gòu)協(xié)議: <SpringSecurity整合oauth2.0 授權(quán)平臺(tái)>

螞蟻課堂
1唠摹,如何保證Api 接口合理安全調(diào)用

2爆捞,OAuth2.0授權(quán)認(rèn)證平臺(tái)設(shè)計(jì)

3,OAuth2.0 認(rèn)證協(xié)議四種模式

4勾拉,oauth2.0實(shí)現(xiàn)對(duì)接口的調(diào)用:

Oauth2.0****模式分類

  1. 授權(quán)碼模式

  2. 簡(jiǎn)化模式

  3. 密碼模式

  4. 客戶端模式
    Oauth2.0模式分類
    1.授權(quán)碼模式
    2.簡(jiǎn)化模式
    3.密碼模式
    4.客戶端模式
    授權(quán)碼模式

授權(quán)碼模式
Maven依賴
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
</parent>


<dependencies>
    <!-- SpringBoot整合Web組件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <!-- springboot整合freemarker -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

    <!-->spring-boot 整合security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- Spring Security OAuth2 -->
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>


    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.62</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
</dependencies>

相關(guān)配置的類

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.
                inMemoryAuthentication()
                .withUser("mayikt")
                .password(passwordEncoder().encode("123456"))
                .authorities("/*");


    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated() //所有請(qǐng)求都需要通過認(rèn)證
                .and()
                .httpBasic() //Basic登錄
                .and()
                .csrf().disable(); //關(guān)跨域保護(hù)
    }
}




@Component
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允許表單提交
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // appid
                .withClient("mayikt")
                // appsecret
                .secret(passwordEncoder.encode("mayikt_secret"))
                // 授權(quán)碼
                .authorizedGrantTypes("authorization_code")
                // 作用域
                .scopes("all")
                // 資源的id
                .resourceIds("mayikt_resource")
                // 回調(diào)地址
                .redirectUris("http://www.mayikt.com/callback");

    }
}




訪問授權(quán)鏈接獲取授權(quán)碼

http://localhost:8080/oauth/authorize?client_id=mayikt&response_type=code

image.png

根據(jù)授權(quán)碼獲取accessToken

接口:http://localhost:8080/oauth/token
Code:授權(quán)碼
grant_type:authorization_code
redirect_uri:回調(diào)地址
Scope: 作用域

http://localhost:8080/oauth/token?code=IDXeHy&grant_type=authorization_code&redirect_uri=http://www.mayikt.com/callback&scope=all
訪問/oauth/token401不足

image.png

解決辦法:
需要BasicAuth認(rèn)證授權(quán) 傳遞參數(shù)clent_id煮甥、client_secret


image.png

access_token=dc9bce8a-7657-44bb-b6b6-1e4baecdfd7b

資源端服務(wù)器端
相關(guān)配置的類



/**
 * 資源Server端
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    @Value("${mayikt.appid}")
    private String mayiktAppId;
    @Value("${mayikt.appsecret}")
    private String mayiktAppSecret;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Primary
    @Bean
    public RemoteTokenServices remoteTokenServices() {
        final RemoteTokenServices tokenServices = new RemoteTokenServices();
        //設(shè)置授權(quán)服務(wù)器check_token端點(diǎn)完整地址
        tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        //設(shè)置客戶端id與secret,注意:client_secret值不能使用passwordEncoder加密藕赞!
        tokenServices.setClientId(mayiktAppId);
        tokenServices.setClientSecret(mayiktAppSecret);
        return tokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //設(shè)置創(chuàng)建session策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        //@formatter:off
        //所有請(qǐng)求必須授權(quán)
        http.authorizeRequests()
                .anyRequest().authenticated();
        //@formatter:on
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("mayikt_resource").stateless(true);
    }
}


@RestController
public class MemberService {
    @GetMapping("/getMember")
    public String getMember() {
        return "我是會(huì)員服務(wù)接口";
    }
}




基于令牌訪問接口

127.0.0.1:8081/getMember 訪問該接口


image.png

或者直接在請(qǐng)求中傳遞

Authorization=Bearer a9011867-236b-4751-a508-48ceed63bffc

設(shè)計(jì)綜合oatuh api接口

1.獲取access_token請(qǐng)求(/oauth/token)

http://localhost:8080/oauth/token?code=IDXeHy&grant_type=authorization_code&redirect_uri=http://www.mayikt.com/callback&scope=all

2.檢查頭肯是否有效請(qǐng)求(/oauth/check_token)

<u>http://localhost:8080/oauth/check_token?token=ea2c1b1e-5541-4018-8728-07f1ac87e9e8</u>

3.刷新token

http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=fbde81ee-f419-42b1-1234-9191f1f95be9&client_id=demoClientId&client_secret=demoClientSecret

image.png

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末成肘,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子斧蜕,更是在濱河造成了極大的恐慌双霍,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件批销,死亡現(xiàn)場(chǎng)離奇詭異洒闸,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)均芽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門丘逸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人掀宋,你說我怎么就攤上這事深纲。” “怎么了劲妙?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵湃鹊,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我是趴,道長(zhǎng)涛舍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任唆途,我火速辦了婚禮富雅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘肛搬。我一直安慰自己没佑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布温赔。 她就那樣靜靜地躺著蛤奢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上啤贩,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天待秃,我揣著相機(jī)與錄音,去河邊找鬼痹屹。 笑死章郁,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的志衍。 我是一名探鬼主播暖庄,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼楼肪!你這毒婦竟也來了培廓?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤春叫,失蹤者是張志新(化名)和其女友劉穎肩钠,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體象缀,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蔬将,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了央星。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片霞怀。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖莉给,靈堂內(nèi)的尸體忽然破棺而出毙石,到底是詐尸還是另有隱情,我是刑警寧澤颓遏,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布徐矩,位于F島的核電站,受9級(jí)特大地震影響叁幢,放射性物質(zhì)發(fā)生泄漏滤灯。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一曼玩、第九天 我趴在偏房一處隱蔽的房頂上張望鳞骤。 院中可真熱鬧,春花似錦黍判、人聲如沸豫尽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽美旧。三九已至渤滞,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間榴嗅,已是汗流浹背妄呕。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留录肯,地道東北人趴腋。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像论咏,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子颁井,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354