gpt4 book ai didi

java - 我什么时候应该在 Spring Boot 应用程序中覆盖 Spring Security 的 configure(AuthenticationManagerBuilder auth)?

转载 作者:行者123 更新时间:2023-12-03 11:18:56 25 4
gpt4 key购买 nike

我正在 Spring Boot 应用程序中学习 Spring Security,我有一个非常简单的示例。我看到,如果我评论 configure(AuthenticationManagerBuilder auth)没有区别。如果我使用它,我有相同的输出,我需要使用硬编码的凭据登录。

@Configuration
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// private final MyUserDetailsService myUserDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}

// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(myUserDetailsService);
// }

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
MyUserDetailsS​​ervice 类:
@Service
public class MyUserDetailsService implements UserDetailsService {

private static final String USERNAME = "john";
private static final String PASSWORD = "$2a$10$fDDUFA8rHAraWnHAERMAv.4ReqKIi7mz8wrl7.Fpjcl1uEb6sIHGu";

@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

if (!userName.equals(USERNAME)) {
throw new UsernameNotFoundException(userName);
}

return new User(USERNAME, PASSWORD, new ArrayList<>());
}
}
休息 Controller :
@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
我想知道是否实现 UserDetailsService接口(interface)等效于覆盖 configure(AuthenticationManagerBuilder auth) .谢谢!

最佳答案

UserDetailsService

UserDetailsService is used by DaoAuthenticationProvider for retrievinga username, password, and other attributes for authenticating with ausername and password. Spring Security provides in-memory and JDBCimplementations of UserDetailsService.

You can define custom authentication by exposing a customUserDetailsService as a bean. For example, the following willcustomize authentication assuming that CustomUserDetailsServiceimplements UserDetailsService


UserDetailsS​​ervice 接口(interface)用于检索与用户相关的数据。它有一个名为 的方法loadUserByUsername() 可以覆盖它以自定义查找用户的过程。为了提供我们自己的用户服务,我们需要实现 UserDetailsS​​ervice 接口(interface)。 loadUserByUsername(String username)返回 用户详情 这是 org.springframework.security.core.userdetails 的一部分其中包括 getUsername(), getPassword(), getAuthorities() 进一步用于 Spring 安全的方法。
我们也可以定制 org.springframework.security.core.userdetails.User (这里用作 new User(USERNAME, PASSWORD, new ArrayList<>()) )通过实现 UserDetails 接口(interface)。
在这里,我分享使用 UserDetailsS​​ervice 服务的理想方式
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {

private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);

private final UserRepository userRepository;

public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}

@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);

if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login)
.map(user -> createSpringSecurityUser(login, user))
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}

String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));

}

private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
}
when loadUserByUsername is invoked?
如上所述,它通常由 DaoAuthenticationProvide 实例调用以对用户进行身份验证。例如,当提交用户名和密码时,会调用 UserdetailsS​​ervice 来查找该用户的密码以查看其是否正确。它通常还会提供有关用户的一些其他信息,例如权限和您可能希望为登录用户访问的任何自定义字段(例如电子邮件)
In-Memory Authentication
在这里,您使用了用户名和密码的静态值,可以使用 In-Memory Authentication 进行理想配置。如下。
Spring Security 的 InMemoryUserDetailsManager实现 UserDetailsService为在内存中检索的基于用户名/密码的身份验证提供支持。 InMemoryUserDetailsManager提供 UserDetails的管理通过实现 UserDetailsManager界面。 UserDetails Spring Security 在配置为接受用户名/密码进行身份验证时使用基于身份验证的身份验证。
@Bean
public UserDetailsService users() {
UserDetails user = User.builder()
.username("user")
.password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
配置(AuthenticationManagerBuilder 身份验证)
此方法使用 AuthenticationManagerBuilder它在内部使用 SecurityBuilder 创建一个 AuthenticationManager。允许轻松构建内存身份验证、LDAP 身份验证、基于 JDBC 的身份验证、添加 UserDetailsS​​ervice 和添加
身份验证提供者。
How Spring Security add/configure AuthenticationManagerBuilder?

UserDetailsService interface is equivalent with overriding theconfigure(AuthenticationManagerBuilder auth)


没有

关于java - 我什么时候应该在 Spring Boot 应用程序中覆盖 Spring Security 的 configure(AuthenticationManagerBuilder auth)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64526372/

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