提问者:小点点

任何工作示例如何使用登录表单和github设置oaut2授权服务器?


我正在尝试使用Spring boot设置授权服务器。

该服务器应该能够使用登录/密码表单和github(例如)授权用户。

我希望这张照片有助于更好地理解我想要什么。

登录表单示例:

要求:

  1. 用户必须能够使用登录/密码表单直接登录(通过在浏览器中输入授权服务器的地址)到服务器。
  2. 用户必须能够使用github授权直接登录服务器。
  3. 客户端(另一个应用程序)必须能够使用此授权服务器以登录/密码的形式授权用户(获取access_token等等…)。
  4. 客户端(另一个应用程序)必须能够使用带有github登录按钮的此授权服务器授权用户。

我只能使用代码完成需求列表中的前3点:

@SpringBootApplication
@RestController
@Configuration
@Import(AuthorizationServerSecurityConfiguration.class)
public class SsoApplication extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(SsoApplication.class, args);
    }

    @GetMapping("/")
    public Authentication me() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .oauth2Login();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("123")
                .password(passwordEncoder().encode("123"))
                .roles("USER");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }

}

完整的代码示例可以在githab上查看

作为检查项目3和4的客户,您可以使用带有设置的邮递员来获取令牌:

  • 授权类型:授权码
  • 回调URL:http://localhost:8081/client/login
  • 认证URL:http://localhost:8080/oauth/authorize
  • 访问令牌URL:http://localhost:8080/oauth/token
  • 客户端ID: first-client
  • 客户秘密:没有人会猜测
  • 范围:user_info
  • 状态:测试
  • 客户端身份验证:作为基本身份验证标头发送

我未能实施:

postman控制台出现错误:

Invalid authorization code: 97477114b3ec3c53547d

我会很感激任何帮助。谢谢!


共2个答案

匿名用户

我找到了错误的原因。问题是Postman从授权服务器的github中截获了错误的代码,而不是客户端授权服务器所需的代码。

换句话说,问题出在postman中。为了进行正确的验证,您必须使用成熟的oaut2客户端。

匿名用户

你的代码对我很有效。

但是我在github中创建了自己的“OAuth应用程序”。然后用你的代码,我放入了我的Github应用程序:

主页URL:http://localhost:8080

授权回调URL:http://localhost:8080/login

并且在给按钮并允许应用程序使用github识别我之后,我已经返回了主

...
"authenticated": true,
"principal": {
    "authorities": [
      {
        "authority": "ROLE_USER",
        "attributes": {
          "login": "xxx",
...

如您所见,您的Spring应用程序不是问题,我认为是您的github配置。

编辑:

在Postman控制台中,如果您将注释@EnableOAuth2Sso放在配置SsoApplication中,错误就会消失:

@SpringBootApplication
@RestController
@Configuration
@EnableOAuth2Sso
@Import(AuthorizationServerSecurityConfiguration.class)
public class SsoApplication extends WebSecurityConfigurerAdapter