簡體   English   中英

使用Spring Security創建/注冊新用戶?

[英]Creation / registration new user with spring security?

我正在學習和開發Restful api作為我未來的android應用程序的后端。 而且我使用spring框架。 我使用Spring Security來限制對某些資源的訪問。 我有UserController方法create(params ..)應該創建新用戶。

@RestController
public class UserController {
    private UserService userService;
    private CreateFormValidator createFormValidator;
    @Autowired
    public UserController(UserService userService, CreateFormValidator createFormValidator) {
        this.userService = userService;
        this.createFormValidator = createFormValidator;
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(createFormValidator);
    }

    @RequestMapping(value = "/user/create", method = RequestMethod.POST)
    String create(@RequestBody @Valid CreateForm createForm, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "user_create";
        }
        try {
            userService.create(createForm);
        } catch (DataIntegrityViolationException e) {
            bindingResult.reject("username.exists", "Username already exists");
            return "user_create";
        }
        return "redirect:/login";
    }
}

和安全性配置,現在我僅在此指定我希望所有用戶都允許使用“ user / create /”。

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("user/create").permitAll();
    }
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

但是當我測試它並使用json主體在“用戶/創建”上執行POST

{
  "username" : "name",
  "password" : "1234",
  "repeatedPassword" : "1234"
}

我越來越:

“”錯誤“:”禁止“”消息“:”在請求參數“ _csrf”或標頭“ X-CSRF-TOKEN”上發現無效的CSRF令牌'null“。

您能解釋一下為什么在configure類中對此URL具有allowAll訪問權限時為什么禁止使用它嗎? 以及如何解決? 提前致謝!

看看http://www.codesandnotes.be/2015/02/05/spring-securitys-csrf-protection-for-rest-services-the-client-side-and-the-server-side/

如果您使用的是Rest Client,請包含X-CSRF-TOKEN來請求標頭。 您將從對服務的get請求之一中獲得csrf令牌值。

或者嘗試以下操作:

{
  "username" : "name",
  "password" : "1234",
  "repeatedPassword" : "1234",
  "_csrf" : "token value"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM