gpt4 book ai didi

java - Spring 安全 : register users during runtime

转载 作者:行者123 更新时间:2023-12-05 07:39:37 27 4
gpt4 key购买 nike

我有一个有两个端点的服务:

  1. 公共(public)端点:任何人都可以访问它,并开设一个用户帐户(注册)
  2. protected 端点:只有注册用户才能访问它,方法是将授权 header 用作 HTTP POST 请求的一部分

用例:

  • 用户首先点击公共(public)端点,然后通过 HTTP POST 包含 userName 的 JSON 打开帐户。该服务随后生成密码,并将其作为 JSON 响应传递回用户。
  • 用户从服务中取回密码后,他应该使用此密码(连同他的用户名)访问 protected 端点 通过在授权 header
  • 中传递他的凭据

现在,很明显,需要在运行时注册新用户。

我面临的问题是,当第一个用户在公共(public)端点上注册时,在那之后就不再需要身份验证来访问 protected 端点了!每个凭据都可以使用,甚至没有授权 header 的请求也可以使用。我不确定为什么我会出现这种不良行为,所以任何关于如何解决它的建议都会很棒!

用于打开用户帐户的公共(public)端点

@RequestMapping(method = RequestMethod.POST, value = "/user", produces = "application/json")
public ResponseEntity<UserCreatedResponse> create(@RequestBody String userName) {
// generate user password
String password = service.generatePassword();

// save the user to the local repository
service.save(userName, password);

// use SecurityService to add a new user token --> something fishy here!
security.login(userName, password);


// returns response with a new user password
return new ResponseEntity<UserCreatedResponse>(
new UserCreatedResponse(password),
HttpStatus.CREATED);
}

UserService.java 用于将用户保存到存储库

public void save(String userName, String password) {
repository.save(new User(userName, passwordEncoder.encode(password)));
}

SecurityService.java 用于存储登录凭据:我不确定这是否正确

public void login(String userName, String password) {
// usrDetailsService is the instance of UserDetailsService.java
UserDetails usrDetails = usrDetailsService.loadUserByUsername(userName);

UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(usrDetails, password, usrDetails.getAuthorities());

// authenticate token with the given account details
authManager.authenticate(token);

if (token.isAuthenticated()) {
// provide authentication info to the context
SecurityContextHolder.getContext().setAuthentication(token);
}
}

UserDetailsS​​ervice.java

public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
// this is my custom User class
User user = repository.findById(userName);

// and this is org.springframework.security.core.userdetails.User
return new User(user.getUsername(), user.getPasswordHash(), Collections.emptySet());
}

protected (授权)端点

@RequestMapping(method = RequestMethod.POST, value = "/hello", produces = "application/json")
public String hello(@RequestBody MyRequest request) {
return "Hello, authenticated!";
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

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

http.csrf().disable();
}
}

同样,想要的行为是:

  • 在“localhost:8080/user”上创建新用户帐户
  • 然后点击“localhost:8080/hello”,这需要对上面注册的任何用户进行身份验证,否则会以Unathorized 响应

缺少什么或我做错了什么?

最佳答案

您的安全配置是什么样的?您可以指定应打开哪些页面进行注册:

  /**
* Configures the access rights for the application.
*
* @param http the HttpSecurity context of the application
* @throws Exception some exception.
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//Which URLs are available without any authentication
.antMatchers("/about", "/help", "/imprint", "/register", "/registerExp", "/login**").permitAll()
//Restrict access rights for any relative URL behind /admin/ to the ADMIN role
.antMatchers("/admin/**").hasRole("ADMIN")
//Any request needs to be fully authenticated (remember me does NOT suffice!)
.anyRequest().fullyAuthenticated().and()
//Specify the login process.
.formLogin()
.loginPage("/login")
.failureHandler(authenticationHandler)
.permitAll()
.and().logout().permitAll()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).ignoringAntMatchers("/console/**");

//Disables header security. This allows the use of the h2 console.
http.headers().frameOptions().disable();
}

关于java - Spring 安全 : register users during runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001916/

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