2022新年上班第一天,简单记录下春节期间,给公司项目升级,遇到的一点问题。
公司有个项目之前springboot的版本是1.x,由于注册中心要换成nacos,就不得已的吧springboot版本升级。
升级之后,重新打开登录页面,发现登录不上去了,看控制台消息,spring security oauth2 授权接口401了
小编这里用的授权模式是:密码模式,就是通过用户密码来认证的。
排查过程如下,希望能帮到你:
解决一:
之前低版本授权下,不是需要client_secret参数的,所以就把client_secret参数加上了。
在客户端配置那一块把配置加上去,调用/oauth/token接口的时候,也需要传这个参数
clients.inMemory()
//本项目配置
.withClient(ResourceSystemTypeEnum.CORE.getAppName())
.authorizedGrantTypes("password")
.authorities("ROLE_TRUSTED_CLIENT")
//配置client-secret
.secret(passwordEncoder.encode(LoginConstants.DEFAULT_CLIENT_SECRET))
.scopes("read", "write")
.resourceIds(resourceId)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
解决二:
在oauth2 集成 spring security的时候,没有加认证的方式。
大家都知道在使用spring security的时候,要验证用户名和密码的时候,需要实现UserDetailsService这个接口,这个实现类也要配置到oauth2中。
配置在Oauth2认证授权服务端配置,就是继承了AuthorizationServerConfigurerAdapter类的配置类
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.accessTokenConverter(jwtAccessTokenConverter);
// 这个配置,把实现类注入进来,然后设置进去
endpoints.userDetailsService(userDetailsService);
endpoints.tokenStore(tokenStore);
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持GET,POST请求
}
解决三:
最后通过以上配置,通过postman调用/oauth/token接口,能够正常拿到access_token,但是项目还是不行。
最后发现项目里面,为了方便提供给其他项目使用授权,是由这个项目转发到/oauth/token,这个授权地址,代码如下:
public void getToken(@RequestBody UserDTO userDTO, @RequestParam("client_id") String clientId, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
//用户名和密码解密
String username = new String(RsaUtil.decryptByPrivateKey(userDTO.getUsername()));
String password = new String(RsaUtil.decryptByPrivateKey(userDTO.getPassword()));
StringBuffer oauthTokenUrl = new StringBuffer("/oauth/token?grant_type=password");
oauthTokenUrl.append("&").append(LoginConstants.USERNAME).append("=").append(encodeLoginParam(username));
oauthTokenUrl.append("&").append(LoginConstants.PASSWORD).append("=").append(encodeLoginParam(password));
oauthTokenUrl.append("&").append(LoginConstants.CLIENT_SECRET).append("=").append(LoginConstants.DEFAULT_CLIENT_SECRET);
oauthTokenUrl.append("&").append(LoginConstants.CLIENT_ID).append("=").append(clientId);
// 之前的方式
// httpRequest.getRequestDispatcher(oauthTokenUrl.toString()).forward(httpRequest, httpResponse);
// 换成重定向即可
httpResponse.sendRedirect(oauthTokenUrl.toString());
}



