gpt4 book ai didi

java - Spring Security服务配置

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:22:14 33 4
gpt4 key购买 nike

我正在尝试使用不同的框架构建 Java EE 应用程序原型(prototype)。除安全层外,一切正常。我选择使用配置了 Spring 配置的 Spring Security。

代码是这样的:

Spring 安全配置

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private MyUserDetailsService userDetailsService;

@Override
protected UserDetailsService userDetailsService () {
return this.userDetailsService;
}

@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authenticate")
.failureUrl("/login?error=bad_credentials")
.and()
.logout()
.logoutUrl("/signout")
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.and()
.csrf();
}
}

用户详情服务

@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService
{
public static final Logger log = Logger.getLogger(MyUserDetailsService.class);

public MyUserDetailsService() {
}

@Autowired
private UserDao userDao;

@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
final User user = getSystemUser(userName);
final List<GrantedAuthority> authorities = getUserAuthorities(user);
return buildUserForAuthentication(user, authorities);
}

private User buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
//...
}

private User getSystemUser(String alias) {
//...
}

private List<GrantedAuthority> getUserAuthorities(User user) {
//...
return null;
}
}

我期望这段代码做的是,当用户到达 /login/authenticate 并传递参数时,底层 spring 代码调用我的用户服务,但这从未发生。

我错过了什么?

我正在使用 spring-security 3.2.3.RELEASE。

最佳答案

您应该在扩展了 WebSecurityConfigureAdapter 的 SecurityConfig 类中注册您的自定义身份验证:

@Autowired
private MyUserDetailsService userDetailsService;

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

对于 3.2.3,配置应该是

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService);
}

关于java - Spring Security服务配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27503285/

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