Spring Boot2 Oauth2隐式流 - http:// localhost:8080/oauth/authorize获取访问被拒绝

Ale*_*Man 7 java oauth-2.0 spring-boot swagger-2.0 springfox

我创建了一个Spring Boot 2应用程序,集成了SpringFox Swagger 2.8.0和Implicit Oauth2 Grant,用于身份验证和授权.

该代码工作正常,但当我单击授权按钮时,它重定向到

HTTP://本地主机:8080 /的OAuth /授权RESPONSE_TYPE =令牌的client_id =测试应用程式内用户-id&REDIRECT_URI = HTTP%3A%2F%2Flocalhost%3A8080%2Fwebjars%2Fspringfox-招摇的UI%2Foauth2-将redirect.html&范围=读&状态= U3VuIE9jdCAxNCAyMDE4IDIwOjQyOjUwIEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBUaW1lKQ%3D%3D

但是显示Access Denied,如下所示.

我的完整项目在GitHub可用

MainApplication.java

@EnableSwagger2
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@RestController
public class MainApplication /*extends WebMvcConfigurerAdapter*/
{

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

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

    @Bean
    SecurityConfiguration security() {
      return SecurityConfigurationBuilder.builder()//<19>
          .clientId("test-app-client-id")
          .build();
    }

    @Bean
    SecurityScheme oauth() {
          List<GrantType> grantTypes = new ArrayList<>();
          ImplicitGrant implicitGrant = new ImplicitGrant(new LoginEndpoint("http://localhost:8080/oauth/authorize"),"access_code");
          grantTypes.add(implicitGrant);
          List<AuthorizationScope> scopes = new ArrayList<>();
          scopes.add(new AuthorizationScope("read","Read access on the API"));
        return new OAuthBuilder()
                .name("SECURITY_SCHEME_OAUTH2")
                .grantTypes(grantTypes)
                .scopes(scopes)
                .build();
    }

    @Bean
    public Docket docket()
    {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage(getClass().getPackage().getName()))
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Collections.singletonList(oauth()))
            .apiInfo(generateApiInfo());
    }


    private ApiInfo generateApiInfo()
    {
        return new ApiInfo("Sample Service", "This service is to check Sample Service.", "Version 1.0",
            "Sample Service", "123@test.com", "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0");
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新1

我添加了@AlexanderPetrov建议的安全性和passwordencoder配置.事情进展顺利,当我添加@EnableResourceServer登录屏幕时显示需要完全身份验证才能访问此资源 ,如下所示

在此输入图像描述

任何人都可以帮我这个

Ale*_*rov 2

您需要在代码中进行以下更改

  1. 表单登录配置对于隐式流程是必需的。
  2. 此外,如果我们使用隐式流令牌,将通过授权 url 而不是令牌 url 生成。所以你需要将“/oauth/token”更改为“oauth/authorize”。配置方法如下

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/oauth/authorize").authenticated()
        .and()
        .authorizeRequests().anyRequest().permitAll()
        .and()
        .formLogin().permitAll()
        .and()
        .csrf().disable();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在类中添加密码编码器SecurityConfig并调用它以在globalUserDetails方法中对用户密码进行编码。编码器是必要的,因为您在内存中使用密码。因此,如果没有密码,编码器应用程序将失败并出现错误:

    Encoded password does not look like BCrypt
    
    Run Code Online (Sandbox Code Playgroud)

下面的代码片段

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
    PasswordEncoder passwordEncoder = passwordEncoder();
    auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).
            withUser("bill").password(passwordEncoder.encode("abc123")).roles("ADMIN").and()
            .withUser("$2a$10$TT7USzDvMxMZvf0HUVh9p.er1GGnjNQzlcGivj8CivnaZf9edaz6C")
            .password("$2a$10$TT7USzDvMxMZvf0HUVh9p.er1GGnjNQzlcGivj8CivnaZf9edaz6C").roles("USER");
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。我已经为您的项目创建了分支,但由于 403 而无法推送它。所以所有必要的代码都在我的答案中。