spring security oauth2 client_credentials模式

本文主要简单介绍一下spring security oauth2的client_credentials模式

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

或者

curl -H "Accept: application/json" http://localhost:8080/oauth/token -d "grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret"

返回

{"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

或者

curl -i -X GET http://localhost:8080/api/blog/1?access_token=fe8bcab3-1d33-4ef1-b1d0-bd142a480af2

不过这种把token暴露在url中不是太安全

返回

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!关于Spring Security OAuth2偶发性登录失败的问题,可能有多种原因导致。以下是一些常见的解决方案和调试步骤,供参考: 1. 检查授权服务器配置:确保你的授权服务器配置正确,并且与客户端应用程序的配置一致。检查授权服务器日志以获取任何错误消息或异常。 2. 检查令牌端点:确保令牌端点的URL和参数正确配置,并且与授权服务器的规范一致。检查令牌端点的请求和响应,以确定是否有任何问题。 3. 检查用户认证:确保用户认证机制正确配置,并且与授权服务器的规范一致。验证用户的凭据和身份验证流程是否正确。 4. 检查客户端凭证:确保客户端凭证(Client Credentials)正确配置,并且与授权服务器的规范一致。验证客户端凭证是否有效,并且具有适当的范围和权限。 5. 检查网络连接:偶发性登录失败可能与网络连接问题有关。检查网络连接是否稳定,并且没有阻止或限制请求的防火墙或代理。 6. 调试日志:在Spring Security配置中启用调试日志,以捕获更多详细信息。查看日志以获取任何异常、错误或警告消息。 7. 测试工具:使用Postman或类似的工具测试授权服务器和令牌端点。确保请求和响应正常,并且没有任何问题。 如果以上步骤都没有解决问题,请提供更多详细信息,例如错误消息、日志输出或代码片段,以便我们更好地帮助你解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值