2017-10-28 109 views
0

我有一个用例,我想HTTP POST a userName作为JSON到我的服务,然后服务应注册一个新用户(给定userName和一个自动生成密码)。弹簧安全:公共API注册新用户

JSON

{ 
"userName": "Sia" 
} 

我使用Spring Security,而且我现在面临的问题是:

每当我试着HTTP POST一个userName,该服务已经要求进行身份验证(用户名和密码)。这不是我想要的。我希望注册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通过spring security的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形RL是permitte所有的安全配置:

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

如果遇到与CSRF保护问题,你可以用

@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配置。

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

嗯,该方法应该在哪里?这是什么模块的一部分? – wesleyy

+0

您的Spring安全性的配置在您加载用户名和密码的地方 – idipous

+0

嗯,我从来没有真正加载它们......它是一个运行时服务,我只有一个存储库,所有用户都是从HTTP POST完全填充的。我想我应该用这种方法添加某种配置类? – wesleyy