Spring Boot2 Oauth2 隐式流程 - http://localhost:拒绝访问

我创建了一个 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 上可用


主应用程序


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

    }

http://img2.mukewang.com/6194ae48000118a205820197.jpg

胡子哥哥
浏览 295回答 2
2回答

慕无忌1623718

当您启用资源服务器时,您需要配置 check_token URL,以便它可以访问 OAuth2 授权服务器并验证给定的 access_token。你可以这样做:@Configuration@EnableResourceServer@EnableGlobalMethodSecurity(prePostEnabled = true)public class OAuth2ResourceServerConfig extends GlobalMethodSecurityConfiguration {&nbsp; &nbsp; @Value("${oauth.url.internal}")&nbsp; &nbsp; // e.g. http://localhost:8082/oauth&nbsp; &nbsp; private String oauthUrl;&nbsp; &nbsp; @Value("${oauth.client}")&nbsp; &nbsp; private String oauthClient;&nbsp; &nbsp; @Value("${oauth.secret}")&nbsp; &nbsp; private String oauthSecret;&nbsp; &nbsp; @Override&nbsp; &nbsp; protected MethodSecurityExpressionHandler createExpressionHandler() {&nbsp; &nbsp; &nbsp; &nbsp; return new OAuth2MethodSecurityExpressionHandler();&nbsp; &nbsp; }&nbsp; &nbsp; @Primary&nbsp; &nbsp; @Bean&nbsp; &nbsp; public RemoteTokenServices tokenService() {&nbsp; &nbsp; &nbsp; &nbsp; RemoteTokenServices tokenService = new RemoteTokenServices();&nbsp; &nbsp; &nbsp; &nbsp; tokenService.setCheckTokenEndpointUrl(oauthUrl + "/check_token");&nbsp; &nbsp; &nbsp; &nbsp; tokenService.setClientId(oauthClient);&nbsp; &nbsp; &nbsp; &nbsp; tokenService.setClientSecret(oauthSecret);&nbsp; &nbsp; &nbsp; &nbsp; return tokenService;&nbsp; &nbsp; }}除此之外,您可能想忽略 Swagger 特定的端点:@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void configure(WebSecurity web) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");&nbsp; &nbsp; }}以防万一,这是我为具有 OAuth2 授权的 Swagger 实现的类:@EnableSwagger2@Configurationpublic class SwaggerConfig implements WebMvcConfigurer {&nbsp; &nbsp; private static final String BASE_PACKAGE = "com.somepackage.api";&nbsp; &nbsp; @Value("${oauth.url}")&nbsp; &nbsp; // Make sure this is an external URL, i.e. accessible from Swagger UI&nbsp; &nbsp; private String oauthUrl;&nbsp; &nbsp; @Value("${swagger.scopes}")&nbsp; &nbsp; private String swaggerScopes;&nbsp; &nbsp; @Value("${swagger.urls}")&nbsp; &nbsp; private String swaggerUrls;&nbsp; &nbsp; // Your v2/api-docs URL accessible from the UI&nbsp; &nbsp; @Bean&nbsp; &nbsp; public Docket api(){&nbsp; &nbsp; &nbsp; &nbsp; return new Docket(DocumentationType.SWAGGER_2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .select()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .apis(RequestHandlerSelectors.basePackage(BASE_PACKAGE))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .apis(RequestHandlerSelectors.any())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .paths(PathSelectors.any())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .build()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .securitySchemes(Collections.singletonList(securitySchema()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .securityContexts(Collections.singletonList(securityContext()));&nbsp; &nbsp; }&nbsp; &nbsp; private OAuth securitySchema() {&nbsp; &nbsp; &nbsp; &nbsp; List<AuthorizationScope> authorizationScopeList = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; authorizationScopeList.add(new AuthorizationScope(swaggerScopes, ""));&nbsp; &nbsp; &nbsp; &nbsp; List<GrantType> grantTypes = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(oauthUrl + "/token");&nbsp; &nbsp; &nbsp; &nbsp; grantTypes.add(creGrant);&nbsp; &nbsp; &nbsp; &nbsp; return new OAuth("oauth2schema", authorizationScopeList, grantTypes);&nbsp; &nbsp; }&nbsp; &nbsp; private SecurityContext securityContext() {&nbsp; &nbsp; &nbsp; &nbsp; return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant(swaggerUrls)).build();&nbsp; &nbsp; }&nbsp; &nbsp; private List<SecurityReference> defaultAuth() {&nbsp; &nbsp; &nbsp; &nbsp; final AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];&nbsp; &nbsp; &nbsp; &nbsp; authorizationScopes[0] = new AuthorizationScope(swaggerScopes, "");&nbsp; &nbsp; &nbsp; &nbsp; return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void addResourceHandlers(ResourceHandlerRegistry registry) {&nbsp; &nbsp; &nbsp; &nbsp; registry.addResourceHandler("swagger-ui.html")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .addResourceLocations("classpath:/META-INF/resources/");&nbsp; &nbsp; &nbsp; &nbsp; registry.addResourceHandler("/webjars/**")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .addResourceLocations("classpath:/META-INF/resources/webjars/");&nbsp; &nbsp; }}版本:springSecurityVersion = '2.0.5.RELEASE'swaggerVersion = '2.8.0'springBootVersion = '2.0.5.RELEASE'

茅侃侃

您需要在代码中进行以下更改隐式流需要表单登录配置。此外,如果我们使用隐式流令牌将通过授权 url 而不是令牌 url 生成。所以你需要把“/oauth/token”改成“oauth/authorize”。下面配置方法@Overrideprotected void configure(HttpSecurity http) throws Exception {&nbsp; &nbsp; http.authorizeRequests().antMatchers("/oauth/authorize").authenticated()&nbsp; &nbsp; .and()&nbsp; &nbsp; .authorizeRequests().anyRequest().permitAll()&nbsp; &nbsp; .and()&nbsp; &nbsp; .formLogin().permitAll()&nbsp; &nbsp; .and()&nbsp; &nbsp; .csrf().disable();}在SecurityConfig类中添加密码编码器,并在globalUserDetails方法中调用它对用户密码进行编码。编码器是必需的,因为您在内存中使用密码。所以没有密码编码器应用程序失败并出现错误:Encoded password does not look like BCrypt下面的代码片段@Autowiredpublic void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {&nbsp; &nbsp; PasswordEncoder passwordEncoder = passwordEncoder();&nbsp; &nbsp; auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; withUser("bill").password(passwordEncoder.encode("abc123")).roles("ADMIN").and()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withUser("$2a$10$TT7USzDvMxMZvf0HUVh9p.er1GGnjNQzlcGivj8CivnaZf9edaz6C")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .password("$2a$10$TT7USzDvMxMZvf0HUVh9p.er1GGnjNQzlcGivj8CivnaZf9edaz6C").roles("USER");}@Beanpublic PasswordEncoder passwordEncoder() {&nbsp; &nbsp; return new BCryptPasswordEncoder();}希望能帮助到你。我已经为您的项目创建了分支,但由于 403 无法推送它。所以所有必要的代码都在我的答案中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java