草庐IT

java - Spring Boot2 Oauth2 隐式流程 - http ://localhost:8080/oauth/authorize getting Access Denied

coder 2024-03-20 原文

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

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

http://localhost:8080/oauth/authorize?response_type=token&client_id=test-app-client-id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fwebjars%2Fspringfox-swagger-ui%2Foauth2-redirect.html&scope=read&state=U3VuIE9jdCAxNCAyMDE4IDIwOjQyOjUwIEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBUaW1lKQ%3D%3D

但显示拒绝访问,如下所示。

我的完整项目在 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");
    }
}

更新1

我已经添加了 @AlexanderPetrov 建议的安全性和密码编码器配置。一切正常,当我添加 @EnableResourceServer 时,我的登录屏幕显示需要完整身份验证才能访问此资源,如下所示

谁能帮我解决这个问题

最佳答案

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

  1. 表单登录配置是隐式流程所必需的。
  2. 此外,如果我们使用隐式流, token 将通过授权 url 而不是 token 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();
    }
    
  3. SecurityConfig 类中添加密码编码器,并在globalUserDetails 方法中调用它对用户密码进行编码。编码器是必需的,因为您使用内存密码。因此,如果没有密码编码器,应用程序将失败并出现错误:

    Encoded password does not look like BCrypt
    

下面的代码片段

@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();
}

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

关于java - Spring Boot2 Oauth2 隐式流程 - http ://localhost:8080/oauth/authorize getting Access Denied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52804707/

有关java - Spring Boot2 Oauth2 隐式流程 - http ://localhost:8080/oauth/authorize getting Access Denied的更多相关文章

  1. ruby-on-rails - Rails 两条腿的 OAuth 提供商? - 2

    我有一个Rails2.3.5应用程序,其中包含我希望保护的API。没有用户-它是一个应用到应用风格的网络服务(更像是亚马逊服务而不是facebook),所以我想使用两条腿的OAuth方法来实现它。我一直在尝试使用oauth-plugin服务器实现作为开始:http://github.com/pelle/oauth-plugin...但它的构建需要三足(网络重定向流)oauth。在我深入研究对其进行更改以支持两条腿之前,我想看看是否有更简单的方法,或者是否有人有更好的方法让Rails应用程序实现成为两条腿的OAuth提供程序。 最佳答案

  2. ruby-on-rails - Rails 4.2.0.beta2 - 无法连接到 LocalHost? - 2

    我按照RailsTutorial.org第三版(刚刚发布的版本)中的说明安装了Rails4.2.0.beta2。我没有使用cloudIDE,而是在带有RVM的Windows7主机上通过Vagrant使用UbuntuTrusty32。rails_4.2.0.beta2_newhello_app然后粘贴到hisgemfilesample中。在那之后,我跑了:$bundleinstall$railss服务器启动正常,但是当我尝试连接到localhost:3000时,出现“找不到服务器”更奇怪的是,我还有几个其他的Rails入门项目,我一直在使用Rails4.0.3和4.1.6,我能够很好地连

  3. ruby - 如何使用 omniauth/oauth 对每秒登录数进行基准测试? ( ruby +rspec) - 2

    我想用一个(自己的)omniauth提供商来衡量每秒可以登录多少次。我需要了解此omniauth/oauth请求的性能如何,以及此身份验证是否具有可扩展性?到目前为止我得到了什么:defperformance_auth(user_count=10)bm=Benchmark.realtimedouser_count.timesdo|n|forkdoclick_on'Logout'omniauth_config_mock(:provider=>"foo",:uid=>n,:email=>"foo#{n}@example.net")visit"/account/auth/foo/"enden

  4. ruby-on-rails - 如何编写 Rails 4 测试以使用 omniauth-google-oauth2 gem 创建 session ? - 2

    我正在尝试为使用omniauth-google-oauth2gem创建session编写测试。我是否需要将env["omniauth.auth"]变量与post:create一起传递?也许当我试图这样做时,我做错了。我得到的错误如下所示...Rake测试错误1)Error:SessionsControllerTest#test_should_get_create:NoMethodError:undefinedmethod`provider'fornil:NilClassapp/models/user.rb:6:in`from_omniauth'app/controllers/sessi

  5. ruby-on-rails - 将 OAuth 与 ActiveResource 一起使用的最简单方法是什么? - 2

    我正在使用一些旧代码并使用ActiveResource进行非常基本的Twitter集成。我想尽可能少地接触应用程序代码,并在仍然使用ActiveResource的同时引入OAuth。不幸的是,我找不到简单的方法来做到这一点。我确实遇到了oauth-active-resourcegem,但它并没有完全记录下来,而且它似乎是为创建完整的API包装器库而设计的。您可以想象,我想避免为这一遗留更改创建整个TwitterActiveResourceAPI包装器。有什么成功案例吗?在我的例子中,离开ActiveResource可能比让它工作更快。我很高兴被证明是错误的!

  6. ruby-on-rails - rails 中的 Omniauth-twitter:OAuth::Unauthorized 401 - 2

    我在使用Twitter进行基本的omniauth身份验证时被封锁了2天。我在简单的omniauth上跟随RyanBates的railscast,但无法通过OAuth::Unauthorized401异常,当我尝试登录时引发。请帮忙!我的代码粘贴在下面:twitterinfo:website:[http://127.0.0.1:3000]callbarckurl:[http://127.0.0.1:3000/auth/twitter/callback]//路线.rbSentimentalist::Application.routes.drawdoresources:dashboard,o

  7. ruby-on-rails - Faraday::ConnectionFailed,Connection refused - connect(2) for “localhost” port 9200 Error Ruby on Rails - 2

    我正在尝试使用RubyonRails在我的应用程序中添加Searchkickgem,但是当我在搜索框中键入一个词时,我的应用程序中出现此错误。我已经根据需要安装了elasticsearch和最新版本的java,但错误仍然是一样的。这是我得到的错误:Faraday::ConnectionFailedinPostsController#searchConnectionrefused-connect(2)for"localhost"port9200这是我的代码:终端显示已安装Elasticsearch:终端Warning:elasticsearch-1.7.3alreadyinstalled

  8. springboot定时任务 - 2

    如果您希望在Spring中启用定时任务功能,则需要在主类上添加 @EnableScheduling 注解。这样Spring才会扫描 @Scheduled 注解并执行定时任务。在大多数情况下,只需要在主类上添加 @EnableScheduling 注解即可,不需要在Service层或其他类中再次添加。以下是一个示例,演示如何在SpringBoot中启用定时任务功能:@SpringBootApplication@EnableSchedulingpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.ru

  9. 基于SpringBoot的线上日志阅读器 - 2

    软件特点部署后能通过浏览器查看线上日志。支持Linux、Windows服务器。采用随机读取的方式,支持大文件的读取。支持实时打印新增的日志(类终端)。支持日志搜索。使用手册基本页面配置路径配置日志所在的目录,配置后按回车键生效,下拉框选择日志名称。选择日志后点击生效,即可加载日志。windows路径E:\java\project\log-view\logslinux路径/usr/local/XX历史模式历史模式下,不会读取新增的日志。针对历史文件可以分页读取,配置分页大小、跳转。历史模式下,支持根据关键词搜索。目前搜索引擎使用的是jdk自带类库,搜索速度相对较低,优点是比较简单。2G日志全文搜

  10. springboot使用validator进行参数校验 - 2

    1.依赖导入org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-validation2.validation常用注解@Null被注释的元素必须为null@NotNull被注释的元素不能为null,可以为空字符串@AssertTrue被注释的元素必须为true@AssertFalse被注释的元素必须为false@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@D

随机推荐