gpt4 book ai didi

java - 无法为 spring security 提供自定义身份验证提供程序

转载 作者:行者123 更新时间:2023-11-30 10:46:56 24 4
gpt4 key购买 nike

我想要一个用于 spring security 的自定义身份验证提供程序,我已经像这样实现了它

@Component
public class ApiCustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

System.out.println("ahsgdvjasdhgjasjdh");
return new UsernamePasswordAuthenticationToken("aman", "12345");
}
@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));


}
}

现在我没有任何逻辑,因为我只是想看看 spring security 是否真的在使用这个身份验证提供程序。

我有我的安全配置文件

@Configuration
@EnableWebSecurity
//@ImportResource("classpath:/security/spring_saml_sso_security.xml")

public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*@Autowired
MetadataGeneratorFilter metadataGeneratorFilter;
@Autowired
FilterChainProxy samlFilter;
@Autowired
SAMLEntryPoint samlEntryPoint;
*/

@Autowired
private CustomUserDetailsService customUserDetailsService;




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

try {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/static/**").permitAll()
.antMatchers("/settings/api/**").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.loginProcessingUrl("/login")
// .usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("/index",true)
.and()
.httpBasic();
// .defaultSuccessUrl("/", true);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("sadhiasdniaaaaaaaaaaaaaaaa:");
e.printStackTrace();
}
}
@Bean
public ApiCustomAuthenticationProvider apiCustomAuthenticationProvider() {
return new ApiCustomAuthenticationProvider();
}
}

我想知道这是不是

@Bean
public ApiCustomAuthenticationProvider apiCustomAuthenticationProvider() {
return new ApiCustomAuthenticationProvider();

是告诉 spring security 使用自定义身份验证管理器的正确方法。

最佳答案

您需要在 Spring 安全配置中添加:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new ApiCustomAuthenticationProvider());
}

auth.authenticationProvider(apiCustomAuthenticationProvider())

提醒一下,如果您返回 token :

用户名密码AuthenticationToken("aman", "12345"),

spring 不会给用户授权。相反,您需要分配角色:

List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
UsernamePasswordAuthenticationToken("aman", "12345",grantedAuths) ;

如上所述,您授予用户 ROLE_USER 然后用户可以使用所有经过身份验证的页面。

希望对您有所帮助。

关于java - 无法为 spring security 提供自定义身份验证提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325651/

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