• 解决Spring Security OAuth在访问/oauth/token时候报401 authentication is required


    抓狂的身份认证

    出现这个问题的具体原因一般有以下两点:

    1.在授权的部分我们一般是通过使用自己的login action进行http basic的方式进行授权,而我们在使用Spring Security的时候只对外暴露了登陆的这个接口,就是说其它的接口都在Spring Security的保护范围内了,包括/oauth的接口。

    2.在通过1的post方式授权通过之后使用/oauth/authorize?grant_type=password&username=user&password=pwd&client_id=app&response_type=code&redirect_uri=http://localhost的方式进行授权,这样是可以的,但是在接下来通过post方式向/oauth/token这个接口获取access_token的时候,会发现这个时候authentication用的并不是前面授权通过的那个authentication,而是使用的匿名登陆的那个authentication,这样前面的authentication就无法正常使用,也会因此而得到401 authentication is required。

    我们可以通过如下的方式解决这个问题 ,在AuthenticationServerConfig这个配置中,启用AuthenticationServerSecurityConfiguration的allowFormAuthenticationForClients允许client使用form的方式进行authentication的授权,具体可以参考如下代码:

    @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    //        super.configure(security);
            // 认证服务器安全配置
            security.passwordEncoder(new PasswordEncoder() {
                @Override
                public String encode(CharSequence charSequence) {
                    // 密码加密
                    return null;
                }
    
                @Override
                public boolean matches(CharSequence charSequence, String s) {
                    // 密码校验
    //                return false;
                    return true;
                }
            })
            .allowFormAuthenticationForClients();
        }
    

      再模拟走一遍

    访问

    http://127.0.0.1:9999/oauth/authorize?client_id=my_client_id&response_type=code&redirect_uri=http://127.0.0.1:10000/auth
    

      

     成功

    http://127.0.0.1:9999/oauth/token
    
    {
    "access_token": "ac1898d6-dfe4-41cd-9f51-9ba5c8602517",
    "token_type": "bearer",
    "refresh_token": "5c3db55a-acab-4d29-988c-3f2d49cda91d",
    "expires_in": 16,
    "scope": "read"
    }
    

      

  • 相关阅读:
    iOS7中都Bar的透明问题
    iOS 如何使用自定义字体
    iOS xib中TableView创建的2种模式
    iOS 保存CGRect,CGPoint到NSArray'的方法
    iOS 中通过使用Google API获得Google服务
    转载一篇ios7的新API文章
    移动开发常用的第三方控件下载网页
    iOS 查看系统字体效果的网页
    iOS 基于UIWebView的应用特点
    Cocos2d 中的Sprite大小调整问题
  • 原文地址:https://www.cnblogs.com/song-wentao/p/7526972.html
Copyright © 2020-2023  润新知