简体   繁体   中英

Spring security: public API to register new user

I have a use-case where I want to HTTP POST a userName as JSON to my service, and the service should then register a new user (with a given userName and an auto-generated password).

JSON

{
"userName": "Sia"
}

I am using Spring Security , and the problem I am facing is that:

Whenever I try to HTTP POST a userName , the service already asks for authentication (username and password). This is not why I want. I want a registration API to be completely public. Meaning that everyone (unauthorized) can HTTP POST a new username and thus "open the account".

I am not sure how I could achieve the wanted behaviour. Parts of the service should be public (like creating a new user as described above), and some parts should indeed require authentication (of the users that are created in the described public POST procedure). Any advice?

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

You can have a URL that is permitte by all in your security configuration:

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

In case you face issues with CSRF protection you can deactivate it with

@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

And use the above in the http configuration.

http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher)

You can try below code to permit /user POST request through spring security.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

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

    }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM