您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何解決SpringSecurity自定義AuthenticationProvider無法@Autowire的問題,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
在AuthenticationProvider中使用@Autowired注入時始終報Null問題
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{
應該使用@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.authenticationProvider(new CustomAuthenticationProvider()); }
好了,這就可以實現AuthenticationProvider時自由的使用@Autowired了
<authentication-manager> <authentication-provider ref="myAuthenticationProvider" /> </authentication-manager> <beans:bean id="userDetailsService" class="net.mantis.security.auth.NMUserDetailsService"/> <beans:bean id="myAuthenticationProvider" class="net.mantis.security.auth.MyAuthenticationProvider"> <beans:property name="userDetailsService"> <beans:bean class="net.mantis.security.auth.NMUserDetailsService"> </beans:bean> </beans:property> </beans:bean>
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; } }
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; } }
感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何解決SpringSecurity自定義AuthenticationProvider無法@Autowire的問題”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。