春ブーツ2.0.3のOAuth2セキュリティ:ヘッダにアクセストークンを使用した場合でも、401エラーを取得します

アディツア・クマール:

私は春ブーツ2.0アプリケーションを作成するとのOAuth2セキュリティを有効にしようとしています。私は今のと同じアプリケーションでの認証サーバーとリソースサーバーを持っています。私のクライアントとユーザーの詳細情報だけでなく、生成されたトークンは、(MySQLの)データベースに永続化し、春のドキュメントによって提供されるデータベーススキーマは同じですされています。私は、ヘッダーやポストマンを使用して、体内のユーザーの資格情報に「/ OAuthのトーク​​ン/ /」エンドポイント提供のclientIdとclientSecretを打つとき、私は正常にアクセストークンを取得しています。

{
"access_token": "bef2d974-2e7d-4bf0-849d-d80e8021dc50",
"token_type": "bearer",
"refresh_token": "32ed6252-e7ee-442c-b6f9-d83b0511fcff",
"expires_in": 6345,
"scope": "read write trust"
}

私は、このアクセストークンを使用して、私のREST APIをヒットしようとする。しかし、私は401不正なエラーを取得しています:

{
"timestamp": "2018-08-13T11:17:19.813+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/myapp/api/unsecure"
}

次のように私が当たってる残りのAPIは以下のとおりです。

http:// localhost:8080 / myappに/ API /保護されていません

http:// localhost:8080 / myappに/ API /安全な

myappのは、私のアプリケーションのコンテキストパスです。

春のドキュメントに記載されているように「安全な」APIのために、私は、リクエストヘッダにアクセストークンを提供しました。

Authorization: Bearer bef2d974-2e7d-4bf0-849d-d80e8021dc50

保護されていないAPIのに対し、私はと認証ヘッダなしで試みました。すべての場合において、私は、両方のAPIの同じエラーを取得しています。

私は現在認証されたユーザを印刷しようとすると、また、そのはanonymousUserとして印刷ばかり。

次のように私が欲しいものは以下のとおりです。

1)私は、安全なAPIがアクセストークンをリクエストヘッダで提供されている場合にのみアクセスできるようにしたいです。

2)私は保護されていないAPIが不正なユーザによってアクセスできるようにします。

3)私は現在、安全なURLにアクセスするときSecurityContextHolderを使用してユーザーを認証されるはずです。

次のように私のWebSecurityConfigurerAdapterは以下のとおりです。

@Configuration
@EnableWebSecurity(debug=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
UserDetailsService userDetailsService;

@Autowired
private ClientDetailsService clientDetailsService;

@Bean
public PasswordEncoder userPasswordEncoder() {
    return new BCryptPasswordEncoder(8);
}

@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource);
}

@Autowired
public void configure(AuthenticationManagerBuilder auth) throws 
Exception {
    auth
    .userDetailsService(userDetailsService)
    .passwordEncoder(userPasswordEncoder());
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws 
Exception {
    return super.authenticationManagerBean();
}

@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore 
tokenStore){
    TokenStoreUserApprovalHandler handler = new 
    TokenStoreUserApprovalHandler();
    handler.setTokenStore(tokenStore);
    handler.setRequestFactory(new 
    DefaultOAuth2RequestFactory(clientDetailsService));
    handler.setClientDetailsService(clientDetailsService);
    return handler;
}

@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws 
Exception {
    TokenApprovalStore store = new TokenApprovalStore();
    store.setTokenStore(tokenStore);
    return store;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .cors().disable()
    .anonymous().disable()
    .authorizeRequests()
    .antMatchers("/index.html", "/**.js", "/**.css", "/").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic();
}

ここで私は私の本当のアプリでそれらを使用することを計画していますように私は、アンギュラ6アプリケーションの静的なページを許可しているantMatchersを使用。そして、いや、次の行は、角のアプリケーションの静的なページを許可するように動作しません。

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

次のように私のAuthorizationServerConfigurerAdapterは以下のとおりです。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends 
AuthorizationServerConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
UserDetailsService userDetailsService;

@Autowired
PasswordEncoder passwordEncoder;

@Autowired
TokenStore tokenStore;

@Autowired
private UserApprovalHandler userApprovalHandler;

@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;


@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer
    .tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()")
    .passwordEncoder(passwordEncoder);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
    .tokenStore(tokenStore)
    .userApprovalHandler(userApprovalHandler)
    .authenticationManager(authenticationManager)
    .userDetailsService(userDetailsService);
}
}

次のように私のResourceServerConfigurerAdapterは以下のとおりです。

@Configuration
@EnableResourceServer
public abstract class ResourceServerConfig extends ResourceServerConfigurerAdapter {

private static final String RESOURCE_ID = "resource-server-rest-api";

@Autowired
TokenStore tokenStore;

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
    resources
    .resourceId(RESOURCE_ID)
    .tokenStore(tokenStore);
}

@Override
public void configure(HttpSecurity http) throws Exception {

    http
    .csrf().disable()
    .cors().disable()
    .anonymous().disable()
    .requestMatchers()
    .antMatchers("/api/**").and()
    .authorizeRequests()
    .antMatchers("/api/secure").authenticated()
    .antMatchers("/api/unsecure").permitAll();
}
}

私はSecurityConfigで匿名アクセスを有効にしてpermitAllとしての私のセキュアでないURLを宣言するときしかし、その後、私は、URLのアクセスすることができますよ。

.antMatchers("/api/unsecure", "/index.html", "/**.js", "/**.css", "/").permitAll()

次のように私のコントローラクラスは次のとおりです。

@RestController
@RequestMapping("/api")
public class DemoController {

@GetMapping("/secure")
public void sayHelloFriend() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    System.out.println("Current User: "+authentication.getName());
    System.out.println("Hello Friend");
}

@GetMapping("/unsecure")
public void sayHelloStranger() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    System.out.println("Current User: "+authentication.getName());
    System.out.println("Hello Stranger");
}
}

任意のより多くの情報が必要な場合、私に教えてください。すべてのヘルプは理解されるであろう。しかし、両方としての春ブーツ2.0ない1.5は私の調査結果のとおり、いくつかの重要な違いがありますのでご注意ください。

Niuhuruラング:

追加しよう

@Order(SecurityProperties.BASIC_AUTH_ORDER)

securityConfigのため?そのチェーンは、まずリソースサーバーの設定をチェックします。

そして、あなたの種類のエラーこと、リソースサーバから抽象を削除しないように注意してください場合。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=182183&siteId=1