第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Spring Boot2 Oauth2 隱式流程 - http://localhost:拒絕訪(fǎng)問(wèn)

Spring Boot2 Oauth2 隱式流程 - http://localhost:拒絕訪(fǎng)問(wèn)

胡子哥哥 2021-11-17 15:22:55
我創(chuàng)建了一個(gè) Spring Boot 2 應(yīng)用程序,將 SpringFox Swagger 2.8.0 與隱式 Oauth2 授權(quán)集成到身份驗(yàn)證和授權(quán)中。代碼工作正常,但是當(dāng)我單擊授權(quán)按鈕時(shí),它重定向到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但顯示拒絕訪(fǎng)問(wèn),如下所示。我的完整項(xiàng)目在GitHub 上可用主應(yīng)用程序@EnableSwagger2@SpringBootApplication@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)@RestControllerpublic 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());    }
查看完整描述

2 回答

?
慕無(wú)忌1623718

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊

當(dāng)您啟用資源服務(wù)器時(shí),您需要配置 check_token URL,以便它可以訪(fǎng)問(wèn) OAuth2 授權(quán)服務(wù)器并驗(yàn)證給定的 access_token。


你可以這樣做:


@Configuration

@EnableResourceServer

@EnableGlobalMethodSecurity(prePostEnabled = true)

public class OAuth2ResourceServerConfig extends GlobalMethodSecurityConfiguration {


    @Value("${oauth.url.internal}")    // e.g. http://localhost:8082/oauth

    private String oauthUrl;


    @Value("${oauth.client}")

    private String oauthClient;


    @Value("${oauth.secret}")

    private String oauthSecret;


    @Override

    protected MethodSecurityExpressionHandler createExpressionHandler() {

        return new OAuth2MethodSecurityExpressionHandler();

    }


    @Primary

    @Bean

    public RemoteTokenServices tokenService() {

        RemoteTokenServices tokenService = new RemoteTokenServices();

        tokenService.setCheckTokenEndpointUrl(oauthUrl + "/check_token");

        tokenService.setClientId(oauthClient);

        tokenService.setClientSecret(oauthSecret);

        return tokenService;

    }

}

除此之外,您可能想忽略 Swagger 特定的端點(diǎn):


@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override

    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");

    }

}

以防萬(wàn)一,這是我為具有 OAuth2 授權(quán)的 Swagger 實(shí)現(xiàn)的類(lèi):


@EnableSwagger2

@Configuration

public class SwaggerConfig implements WebMvcConfigurer {


    private static final String BASE_PACKAGE = "com.somepackage.api";


    @Value("${oauth.url}")    // Make sure this is an external URL, i.e. accessible from Swagger UI

    private String oauthUrl;


    @Value("${swagger.scopes}")

    private String swaggerScopes;


    @Value("${swagger.urls}")

    private String swaggerUrls;    // Your v2/api-docs URL accessible from the UI


    @Bean

    public Docket api(){

        return new Docket(DocumentationType.SWAGGER_2)

            .select()

            .apis(RequestHandlerSelectors.basePackage(BASE_PACKAGE))

            .apis(RequestHandlerSelectors.any())

            .paths(PathSelectors.any())

            .build()

            .securitySchemes(Collections.singletonList(securitySchema()))

            .securityContexts(Collections.singletonList(securityContext()));

    }


    private OAuth securitySchema() {

        List<AuthorizationScope> authorizationScopeList = new ArrayList<>();

        authorizationScopeList.add(new AuthorizationScope(swaggerScopes, ""));


        List<GrantType> grantTypes = new ArrayList<>();

        GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(oauthUrl + "/token");

        grantTypes.add(creGrant);


        return new OAuth("oauth2schema", authorizationScopeList, grantTypes);

    }


    private SecurityContext securityContext() {

        return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant(swaggerUrls)).build();

    }


    private List<SecurityReference> defaultAuth() {

        final AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

        authorizationScopes[0] = new AuthorizationScope(swaggerScopes, "");

        return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));

    }


    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {


        registry.addResourceHandler("swagger-ui.html")

                .addResourceLocations("classpath:/META-INF/resources/");


        registry.addResourceHandler("/webjars/**")

                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

}

版本:

  • springSecurityVersion = '2.0.5.RELEASE'

  • swaggerVersion = '2.8.0'

  • springBootVersion = '2.0.5.RELEASE'


查看完整回答
反對(duì) 回復(fù) 2021-11-17
?
茅侃侃

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊

您需要在代碼中進(jìn)行以下更改


隱式流需要表單登錄配置。

此外,如果我們使用隱式流令牌將通過(guò)授權(quán) 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();

}

在SecurityConfig類(lèi)中添加密碼編碼器,并在globalUserDetails方法中調(diào)用它對(duì)用戶(hù)密碼進(jìn)行編碼。編碼器是必需的,因?yàn)槟趦?nèi)存中使用密碼。所以沒(méi)有密碼編碼器應(yīng)用程序失敗并出現(xiàn)錯(cuò)誤:


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

}

希望能幫助到你。我已經(jīng)為您的項(xiàng)目創(chuàng)建了分支,但由于 403 無(wú)法推送它。所以所有必要的代碼都在我的答案中。


查看完整回答
反對(duì) 回復(fù) 2021-11-17
  • 2 回答
  • 0 關(guān)注
  • 329 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)