gpt4 book ai didi

java - Spring 安全: public API to register new user

转载 作者:行者123 更新时间:2023-12-02 02:31:41 24 4
gpt4 key购买 nike

我有一个用例,我想将 userName 作为 JSON 发送到我的服务,然后该服务应该注册一个新用户(使用给定的用户名) 用户名和自动生成的密码)。

JSON

{
"userName": "Sia"
}

我正在使用Spring Security,我面临的问题是:

每当我尝试对 userName 进行 HTTP POST 时,该服务就已经要求进行身份验证(用户名和密码)。这不是我想要的原因。我希望注册 API 完全公开。这意味着每个人(未经授权)都可以 HTTP POST 新用户名,从而“开设帐户”。

我不确定如何实现想要的行为。服务的某些部分应该是公共(public)的(例如如上所述创建新用户),并且某些部分确实应该需要身份验证(在所描述的公共(public) 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));
}

最佳答案

您可以尝试以下代码来通过 Spring Security 允许 /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();

}
}

关于java - Spring 安全: public API to register new user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com