Spring Security Spring Oauth2令牌的客户端交换代码

e3bfsja2  于 2023-01-09  发布在  Spring
关注(0)|答案(1)|浏览(159)

我对Spring Configuration比较陌生,我正在尝试配置一个oauth2client并通过我的外部身份提供者OpenId Connect对其进行身份验证。
当用户第一次访问localhost:8080这样的服务器时,我有一个OpenIDConnectAuthenticationFilter bean,它从IDP重定向到我的身份验证门户:

public class OpenIDConnectAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Value("${my.oauth2.clientId}")
private String clientId;

@Value("${my.oauth2.clientSecret}")
private String clientSecret;

@Value("${my.oauth2.userinfolink}")
private String userinfolink;

@Resource
private OAuth2RestOperations restTemplate;

@Autowired
private MyAuthorityMapper appAuthorityMapper;

protected OpenIDConnectAuthenticationFilter(String defaultFilterProcessesUrl) {
    super(defaultFilterProcessesUrl);
    System.out.println("defaultFilterProcessesUrl :" + defaultFilterProcessesUrl);
    setAuthenticationManager(authentication -> authentication); // AbstractAuthenticationProcessingFilter requires an authentication manager.
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    System.out.println("attemptAuthentication ");
    System.out.println(request.getParameterMap());
    Map<String, String> form = new HashMap<String, String>();
    form.put("client_id", clientId);
    form.put("client_secret", clientSecret);
    ResponseEntity<MyUserInfo> userInfoResponseEntity = null;
    userInfoResponseEntity = restTemplate.getForEntity(userinfolink, MyUserInfo.class, form);

    MyUserInfo myUserInfo = userInfoResponseEntity.getBody();
    List userGroupList = new ArrayList();

    return new PreAuthenticatedAuthenticationToken(myUserInfo, empty(), this.appAuthorityMapper.mapAuthorities(userGroupList));

}
}

我的Oauth2Client是:
但是,当我想用令牌交换代码授权时,我的登录过程停止了

看起来/callback功能没有被执行,并且上面实现的身份验证功能从未进入。
谢谢。

ghhaqwfi

ghhaqwfi1#

看起来您的应用程序需要在不同的路径下进行回调调用。默认情况下,Spring希望交换代码返回到端点{baseUrl}/login/oauth2/code/{registrationId},其中registrationId是您在配置文件中使用的名称。
您可以在以下任一配置文件中进行更改:

spring:
 security:
   oauth2:
     client:
       registration:
         okta:
           client-id: <confidential>
           client-secret: <confidential>
           redirectUri: http://localhost:8080/authorization-code/callback
           scope: openid
           clientName: okta

或者通过实现方法void configure(HttpSecurity http)在代码中实现

@Override
  protected void configure(HttpSecurity http) throws Exception {
     http.oauth2Login()
       .redirectionEndpoint()
       .baseUri("/oauth2/callback/*")

  }

相关问题