当前位置: 首页 > news >正文

spring security oauth2 authorization code模式

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

配置

security config

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 1\这里记得设置requestMatchers,不拦截需要token验证的url
     * 不然会优先被这个filter拦截,走用户端的认证而不是token认证
     * 2\这里记得对oauth的url进行保护,正常是需要登录态才可以
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                .requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .and()
                .formLogin().permitAll();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("demoUser1").password("123456").authorities("USER").build());
        manager.createUser(User.withUsername("demoUser2").password("123456").authorities("USER").build());
        return manager;
    }

    /**
     * support password grant type
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
复制代码

新增formLogin,用于页面授权

resource server config

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/api/**")
                .and()
                .authorizeRequests()
                .antMatchers("/api/**").authenticated();
}
复制代码

oauth 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
                .realm("oauth2-resources")
                .tokenKeyAccess("permitAll()") //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
                .checkTokenAccess("isAuthenticated()") //url:/oauth/check_token allow check token
                .allowFormAuthenticationForClients();
    }
    
    @Autowired
    private AuthenticationManager authenticationManager;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("demoApp")
                .secret("demoAppSecret")
                .redirectUris("http://baidu.com")
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
                        "password", "implicit")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }
}
复制代码

注意,这里要配置redirectUris

请求授权

浏览器访问

http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com
复制代码
  • 没有登录需要先登录

  • 登陆后approve

  • 之后有个code

https://www.baidu.com/?code=p1ancF
复制代码

携带code获取token

curl -i -d "grant_type=authorization_code&code=p1ancF&client_id=demoApp&client_secret=demoAppSecret" -X POST http://localhost:8080/oauth/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: Sun, 03 Dec 2017 08:09:21 GMT
Connection: close

{"error":"invalid_grant","error_description":"Redirect URI mismatch."}
复制代码

url需要传递redirect_uri,另外AuthorizationServerConfigurerAdapter需要配置一致的

需要传递

curl -i -d "grant_type=authorization_code&code=luAJTn&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com" -X POST http://localhost:8080/oauth/token
复制代码

成功返回

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
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 03 Dec 2017 08:17:40 GMT

{"access_token":"c80408d4-5afb-4f87-9538-9fb45b149941","token_type":"bearer","refresh_token":"d59e5113-9174-4258-8915-169857032ed0","expires_in":1199,"scope":"all"}
复制代码

错误返回

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: Sun, 03 Dec 2017 08:17:09 GMT
Connection: close

{"error":"invalid_grant","error_description":"Invalid authorization code: p1ancF"}
复制代码

这个code只能用一次,如果这一次失败了则需要重新申请

携带token请求资源

curl -i http://localhost:8080/api/blog/1?access_token=c80408d4-5afb-4f87-9538-9fb45b149941
复制代码

成功返回

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: text/plain;charset=UTF-8
Content-Length: 14
Date: Sun, 03 Dec 2017 08:19:25 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=c80408d4-5afb-4f87-9538-9fb45b149941
复制代码

返回

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: Sun, 03 Dec 2017 08:20:57 GMT

{"aud":["oauth2-resource"],"exp":1512290260,"user_name":"demoUser1","authorities":["USER"],"client_id":"demoApp","scope":["all"]}
复制代码

这样就大功告成了

doc

  • Implementing OAuth2 with Spring Security

  • OAuth 2.0 筆記 (4.1) Authorization Code Grant Flow 細節

相关文章:

  • 刷新页面清空 input text的值
  • 服务器数据库不用开通远程连接通过工具在本地连接操作的方法
  • 温故·我的笔记
  • 【转】NGUI版虚拟摇杆
  • 探索 DWARF 调试格式信息
  • java静态代码块,静态方法和非静态方法的加载顺序和执行顺序
  • 使用NVelocity0.5实现服务器端页面自动生成
  • 回顾2016
  • secureCRT linux shell显示中文乱码 解决方法
  • json数据url传递到php后台
  • oracle的column格式化导致字段值显示为####的处理办法
  • 为docker配置固定ip
  • 爱上MVC3~将系统的路由设置抽象成对象吧
  • Vue2 SSR 的优化之旅
  • Linux~其实shell脚本也很简单
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • HTTP中的ETag在移动客户端的应用
  • Java读取Properties文件的六种方法
  • MaxCompute访问TableStore(OTS) 数据
  • python 学习笔记 - Queue Pipes,进程间通讯
  • springboot_database项目介绍
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • ViewService——一种保证客户端与服务端同步的方法
  • vue脚手架vue-cli
  • 纯 javascript 半自动式下滑一定高度,导航栏固定
  • 从伪并行的 Python 多线程说起
  • 关于extract.autodesk.io的一些说明
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 优化 Vue 项目编译文件大小
  • 原生Ajax
  • # Pytorch 中可以直接调用的Loss Functions总结:
  • #if #elif #endif
  • #LLM入门|Prompt#1.8_聊天机器人_Chatbot
  • (办公)springboot配置aop处理请求.
  • (二) Windows 下 Sublime Text 3 安装离线插件 Anaconda
  • (分类)KNN算法- 参数调优
  • (附源码)计算机毕业设计SSM基于java的云顶博客系统
  • (入门自用)--C++--抽象类--多态原理--虚表--1020
  • (三)Pytorch快速搭建卷积神经网络模型实现手写数字识别(代码+详细注解)
  • (十)【Jmeter】线程(Threads(Users))之jp@gc - Stepping Thread Group (deprecated)
  • (转)GCC在C语言中内嵌汇编 asm __volatile__
  • (状压dp)uva 10817 Headmaster's Headache
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .NET Core 通过 Ef Core 操作 Mysql
  • .net framework profiles /.net framework 配置
  • .NET Remoting学习笔记(三)信道
  • .net生成的类,跨工程调用显示注释
  • .Net中ListT 泛型转成DataTable、DataSet
  • [Angular] 笔记 21:@ViewChild
  • [C++]运行时,如何确保一个对象是只读的
  • [ChromeApp]指南!让你的谷歌浏览器好用十倍!
  • [Excel] vlookup函数
  • [go 反射] 进阶
  • [go] 迭代器模式
  • [Grafana]ES数据源Alert告警发送