SpringSecurity自定义AuthenticationProvider无法@Autowire的解决

网友投稿 612 2022-11-13

SpringSecurity自定义AuthenticationProvider无法@Autowire的解决

SpringSecurity自定义AuthenticationProvider无法@Autowire的解决

自定义AuthenticationProvider无法@Autowire的解决

在AuthenticationProvider中使用@Autowired注入时始终报Null问题

找了半天发现应该在SecurityConfig配置类中

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter{

在设置AuthenticationProvider时

应该使用@Bean的方式设置

@Bean

CustomAuthenticationProvider customAuthenticationProvider() {

return new CustomAuthenticationProvider();

}

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.authenticationProvider(customAuthenticationProvider());

}

之前的错误的设置方式是

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.ahttp://uthenticationProvider(new CustomAuthenticationProvider());

}

好了,这就可以实现AuthenticationProvider时自由的使用@Autowired了

自定义AuthenticationProvider的简单例子

xml 配置

net.mantis.security.auth.MyAuthenticationProvider

public class MyAuthenticationProvider implements AuthenticationProvider {

UserDetailsService userDetailsService;

public Authentication authenticate(Authentication authentication)

throws AuthenticationException {

//username

System.out.println("user name: "+authentication.getName());

//password

System.out.println("password: "+authentication.getCredentials());

System.out.println("getPrincipal: "+authentication.getPrincipal());

System.out.println("getAuthorities: "+authentication.getAuthorities());

System.out.println("getDetails: "+authentication.getDetails());

UserDetails userDetails = (UserDetails)this.userDetailsService.loadUserByUsername(authentication.getName());

UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(

userDetails, authentication.getCredentials(),userDetails.getAuthorities());

return result;

}

public boolean supports(Class authentication) {

return true;

}

public void setUserDetailsService(UserDetailsService userDetailsService){

this.userDetailsService = userDetailsService;

}

}

net.mantis.security.auth.NMUserDetailsService

public class NMUserDetailsService implements UserDetailsService {

@Override

public UserDetails loadUserByUsername(String userName)

throws UsernameNotFoundException {

ArrayList list = new ArrayList();

list.add(new SimpleGrantedAuthority("ROLE_SUPERVISOR"));

User details = new User("rod", "koala", list);

return details;

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode刷题之旅(简单-7):合并两个有序链表
下一篇:mybatis(4):增删改查(insert+select+update+delete)(上集)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~