2017-10-28 8 views
0

サービスのJSONとしてHTTP POSTuserNameを使用するユースケースがあり、サービスは新しいユーザーを登録する必要があります(指定されたuserNameと自動生成されたパスワード)。春のセキュリティ:新しいユーザーを登録するための公開API

JSON

{ 
"userName": "Sia" 
} 

私はSpring Securityを使用しています、と私は直面しています問題があることである:私はHTTP POSTuserNameを試みるたび

、サービスがすでに認証(ユーザ名とパスワードを要求します)。これは私が欲しいのではない。登録APIを完全に公開したい。つまり、誰もが(許可されていない)HTTP POSTの新しいユーザー名を使用して「アカウントを開く」ことができます。

希望の動作をどのように達成できるかわかりません。サービスの一部は公開されている必要があります(上で説明したように新しいユーザーを作成するようなものです)。一部の部分は実際には公開された公開ユーザーPOSTプロシージャで作成されたユーザーです。何かアドバイス?

のpom.xml

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 

    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-security</artifactId> 
    </dependency> 
    </dependencies> 

UserController.java

@Autowired 
private UserService service;  

@RequestMapping(method = RequestMethod.POST, value = "/user") 
public void register(@PathVariable String userName) { 
    System.err.println("!!!!!!!!!!!"); // this line never gets executed 

    service.save(userName); 
} 

UserService.java

public void save(String userName) {  
    String password = pwGenerator.generate();  
    repository.save(new User(userName, password)); 
} 

答えて

1

/user春のセキュリティを通じてPOSTリクエストを許可するには、次のコードを試してください。

@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(final HttpSecurity http) throws Exception { 

     http.authorizeRequests() 
      .antMatchers(HttpMethod.POST, "/user") 
       .permitAll().anyRequest().authenticated(); 

    } 
} 
1

あなたはUを持つことができます場合

.antMatchers("/user").permitAll() 

あなたが

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

    // Build the request matcher for CSFR protection 
    RequestMatcher csrfRequestMatcher = new RequestMatcher() { 

     // Always allow the HTTP GET method 

     // Disable CSFR protection on the following urls: 
     private AntPathRequestMatcher[] requestMatchers = { 
       new AntPathRequestMatcher("/user") }; 

     @Override 
     public boolean matches(HttpServletRequest request) { 

      if (request.getMethod().matches(GET_METHOD_REGEX)) 
       return false; 

      for (AntPathRequestMatcher rm : requestMatchers) { 
       if (rm.matches(request)) { 
        return false; 
       } 
      } 
      return true; 
     } // method matches 

    }; // new RequestMatcher 

でそれを無効にし、HTTP構成で上記を使用することができますCSRF保護の問題に直面します。セキュリティ構成のすべてによってpermitteあるRL。

http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher) 
+0

ええと、その方法はどこですか?それは何のモジュールですか? – wesleyy

+0

あなたのユーザ名とパスワードをロードするSpringセキュリティの設定 – idipous

+0

まあ、実際にロードすることはありません...ランタイムサービスです。リポジトリにはすべてのユーザがHTTP POSTから専有されています。私はこの方法で何らかの種類の構成クラスを追加すべきだと思いますか? – wesleyy

関連する問題