美文网首页
oAuth2基于内存存储令牌

oAuth2基于内存存储令牌

作者: Lucie_xxm | 来源:发表于2019-04-28 15:38 被阅读0次

    概述

    内存存储令牌 的模式用于演示最基本的操作,快速理解 oAuth2 认证服务器中 "认证"、"授权"、"访问令牌” 的基本概念

    • 配置认证服务器
      • 配置客户端信息:ClientDetailsServiceConfigurer
        • inMemory:内存配置
        • withClient:客户端标识
        • secret:客户端安全码
        • authorizedGrantTypes:客户端授权类型
        • scopes:客户端授权范围
        • redirectUris:注册回调地址
        • 配置 Web 安全
        • 通过 GET 请求访问认证服务器获取授权码
        • 端点:/oauth/authorize
        • 通过 POST 请求利用授权码访问认证服务器获取令牌
        • 端点:/oauth/token

    注: 默认使用springboot启动web项目

    pom

    添加依赖相应的依赖

      <!-- Spring Security -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-oauth2</artifactId>
            </dependency>
        </dependencies>
    

    配置认证服务

    创建一个类继承 AuthorizationServerConfigurerAdapter 并添加相关注解:

    • @Configuration
    • @EnableAuthorizationServer
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    .withClient("client")
                    .secret("secret")
                    .authorizedGrantTypes("authorization_code")
                    .scopes("app")
                    .redirectUris("http://www.baidu.com");
    
        }
    
    }
    

    服务器安全配置

    创建一个类继承 WebSecurityConfigurerAdapter 并添加相关注解:

    • @Configuration
    • @EnableWebSecurity
    • @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true):全局方法拦截
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
    public class WebSecutityConfigurer extends WebSecurityConfigurerAdapter {
    
    }
    

    application.properties

    ## Spring server 
    spring.application.name=oauth2-server
    spring.security.user.name=root
    spring.security.user.password=123456
    server.port=8080
    

    访问获取授权码

    打开浏览器,输入地址:

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

    第一次访问会跳转到登录页面

    验证成功后会询问用户是否授权客户端

    选择授权后会跳转,浏览器地址上还会包含一个授权码(code=1JuO6V),浏览器地址栏会显示如下地址:

    http://www.baidu.com/?code=1JuO6V
    

    有了这个授权码就可以获取访问令牌了

    通过授权码向服务器申请令牌

    通过 CURL 或是 Postman 请求

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=authorization_code&code=1JuO6V' "http://client:secret@localhost:8080/oauth/token"
    

    相关文章

      网友评论

          本文标题:oAuth2基于内存存储令牌

          本文链接:https://www.haomeiwen.com/subject/zskdnqtx.html