专栏首页码匠的流水账spring security oauth2牛刀小试

spring security oauth2牛刀小试

本文主要简单介绍一下如何简单入门spring security oauth2

maven

        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

auth server config

@Configuration
@EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()") //allow check token
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("demoApp")
                .secret("demoAppSecret")
                .authorizedGrantTypes("client_credentials", "password", "refresh_token")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }

}

resource server config

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

}

demo controller

@RestController
@RequestMapping("/api")
public class DemoController {

    @GetMapping("/blog/{id}")
    public String getBlogById(@PathVariable long id) {
        return "this is blog "+id;
    }
}

验证

没有token请求资源

curl -i -H "Accept: application/json" -X GET http://localhost:8080/api/blog/1

返回

HTTP/1.1 401
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Cache-Control: no-store
Pragma: no-cache
WWW-Authenticate: Bearer realm="oauth2-resource", error="unauthorized", error_description="Full authentication is required to access this resource"
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 02 Dec 2017 14:31:51 GMT

{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

client_credentials请求授权

curl -H "Accept: application/json" demoApp:demoAppSecret@localhost:8080/oauth/token -d grant_type=client_credentials

返回

{"access_token":"6d0ee2b2-c803-49bf-a813-a25bfb59a976","token_type":"bearer","expires_in":1199,"scope":"all"}

携带token请求资源

curl -i -H "Accept: application/json" -H "Authorization: Bearer 6d0ee2b2-c803-49bf-a813-a25bfb59a976" -X GET http://localhost:8080/api/blog/1

返回

HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Application-Context: application
Content-Type: application/json;charset=UTF-8
Content-Length: 14
Date: Sat, 02 Dec 2017 14:31:09 GMT

this is blog 1

check token

curl -i -X POST -H "Accept: application/json" -u "demoApp:demoAppSecret" http://localhost:8080/oauth/check_token?token=3d47e053-de16-4e6f-8ec7-f9247f425a8e

返回

HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 02 Dec 2017 14:50:32 GMT

{"timestamp":1512226232386,"status":403,"error":"Forbidden","message":"Access is denied","path":"/oauth/check_token"}

需要配置

@Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()") //allow check token
                .allowFormAuthenticationForClients();
    }

成功返回

HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Application-Context: application
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 02 Dec 2017 14:48:33 GMT

{"aud":["oauth2-resource"],"scope":["read"],"exp":1512227200,"client_id":"demoApp"}

token非法

HTTP/1.1 400
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Application-Context: application
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 02 Dec 2017 14:51:33 GMT
Connection: close

{"error":"invalid_token","error_description":"Token was not recognised"}

doc

  • Trying out OAuth2 via CURL
  • 403 Forbidden on /oauth/check_token #28
  • How to obtain refresh token when using client credentials? #195
  • Spring OAuth Authorization Server Requires Scope
  • Spring Security OAuth2 – Simple Token Revocation

本文分享自微信公众号 - 码匠的流水账(geek_luandun),作者:patterncat

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2017-12-02

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • spring security oauth2 authorization code模式

    前面两篇文章讲了client credentials以及password授权模式,本文就来讲一下authorization code授权码模式。

    codecraft
  • spring security oauth2之refresh token

    本文就来讲一讲spring security oauth2的refresh token方式

    codecraft
  • 聊聊skywalking的lettuce-plugin

    skywalking-6.6.0/apm-sniffer/optional-plugins/lettuce-5.x-plugin/src/main/resour...

    codecraft
  • ★Kali信息收集~4.DNS系列

    ★.1host:DNS信息 参数: ? 一般情况下,host查找的是A,AAAA,和MX的记录 ? 案例: DNS服务器查询 host -t ns 域名 ? ...

    逸鹏
  • 基于TensorFlow和Keras的图像识别

    TensorFlow和Keras最常见的用途之一是图像识别/分类。通过本文,您将了解如何使用Keras达到这一目的。

    小白学视觉
  • Java 实现区块链中的区块,BLOCK的实现

    区块6个属性的说明-Hash 区块的hash值是整个区块各个内容整体计算出的hash值

    吴生
  • 支持了Unicode及各国字符集编码识别]改善IDA6.8对中文等非英语国家的ANSI字符串显示支持不佳的问题

    int _tmain(int argc, _TCHAR* argv[]) { printf("%s","我是中国人"); ...

    战神伽罗
  • fpm制作rpm包

    在Linux系统中,RPM包的制作是很困难的,其实使用工具就能快速制作RPM包,简单易学,下面小编就给大家介绍下Linux使用FPM制作RPM包的方法,感兴趣的...

    菲宇
  • 系统工程的本质

    原文链接:https://mp.weixin.qq.com/s/9uTG1QyjOzIfeMuvioNkWw

    月牙寂道长
  • 玩转 Linux 之:磁盘分区、挂载知多少?

    上周在做日志机扩容的时候,发现运维同学将一块硬盘的挂载点没有同以前的日志机保持一致,考虑到这会给日后的维护带来麻烦,于是尝试着手修改,在修改的同时,revie...

    用户1177713

扫码关注云+社区

领取腾讯云代金券