Spring Security自定義認證器的實現代碼
在了解過Security的認證器后,如果想自定義登陸,只要實現AuthenticationProvider還有對應的Authentication就可以了
Authentication
首先要創(chuàng)建一個自定義的Authentication,Security提供了一個Authentication的子類AbstractAuthenticationToken
我們實現這個類可以了,他已經實現了Authentication的一些方法
public class NamePassAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 520L; private final Object principal; private Object credentials; //提供第一次進來的構造方法 public NamePassAuthenticationToken(Object principal, Object credentials) { super((Collection)null); this.principal = principal; this.credentials = credentials; this.setAuthenticated(false); } //提供填充Authentication的構造方法 public NamePassAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; this.credentials = credentials; super.setAuthenticated(true); } @Override public Object getCredentials() { return this.credentials; } @Override public Object getPrincipal() { return this.principal; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated) { throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } else { super.setAuthenticated(false); } } @Override public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } }
這個類關鍵就是一個是認證的,一個沒認證的的構造器
AuthenticationProvider
接著是AuthenticationProvider,需要實現他的authenticate方法
@Setter public class NamePassAuthenticationProvider implements AuthenticationProvider { private CustomUserDetailsService userDetailsService; private PasswordEncoder passwordEncoder; @Override //具體認證邏輯 public Authentication authenticate(Authentication authentication) { NamePassAuthenticationToken authenticationToken = (NamePassAuthenticationToken) authentication; String username = (String) authenticationToken.getPrincipal(); String password = (String) authenticationToken.getCredentials(); //讓具體認證類去認證 UserDetails user = userDetailsService.loadUserByUsername(username); boolean matches = passwordEncoder.matches(password, user.getPassword()); if (!matches) { ResMsg.throwException(AuthExceptionGroup.AUTH_ERROR); } //填充Authentication NamePassAuthenticationToken authenticationResult = new NamePassAuthenticationToken(user, password, user.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } @Override //指定具體的Authentication //根據你指定的Authentication來找到具體的Provider public boolean supports(Class<?> authentication) { return NamePassAuthenticationToken.class.isAssignableFrom(authentication); } }
SecurityConfigurerAdapter
接著就是填充配置了
@Component public class NamePassAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private CustomUserDetailsService customUserDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override public void configure(HttpSecurity http) { //phonePass provider NamePassAuthenticationProvider provider = new NamePassAuthenticationProvider(); provider.setUserDetailsService(customUserDetailsService); provider.setPasswordEncoder(passwordEncoder); http.authenticationProvider(provider); } }
接下來就是導入配置了
通常都會有一個實現了WebSecurityConfigurerAdapter的配置類
把配置類注入進來
@Autowired private NamePassAuthenticationSecurityConfig namePassAuthenticationSecurityConfig; protected void configure(HttpSecurity http) throws Exception { http.apply(namePassAuthenticationSecurityConfig); }
UserDetailsService
UserDetailsService是具體的認證實現類
這個類就非常熟悉了,只需要實現他的loadUserByUsername方法,就可以實現認證了
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AuthmsViewAccount account = accountService.getAccount(username); if(account == null) { ResMsg.throwException(AUTH_ERROR); } if (account.getStatus() != 1) { ResMsg.throwException(ACCOUNT_HAS_BANED); } String spliceStaffInfo = String.format("%d-%s",account.getAccountId(),account.getUsername()); //只要Collection<? extends GrantedAuthority> authorities //這個參數不為空,就表明認證通過,所以空集合也可以通過 return new User(spliceStaffInfo,account.getPassword(), AuthorityUtils.NO_AUTHORITIES); }
把認證結果填充到上下文中
TokenFilter
如果結合了Token,那么需要從token中識別該用戶
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String bearerToken = resolveToken(request); if (bearerToken != null && !"".equals(bearerToken.trim()) && SecurityContextHolder.getContext().getAuthentication() == null) { //從redis中獲取該用戶 NamePassAuthenticationToken namePassAuthenticationToken = authRedisHelper.get(bearerToken); if(namePassAuthenticationToken != null) { //將信息保存到上下文中 SecurityContextHolder.getContext().setAuthentication(namePassAuthenticationToken); } } chain.doFilter(request, response); } private String resolveToken(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { return bearerToken.substring(7); } return null; }
public NamePassAuthenticationToken get(String bearerToken){ String spliceStaffInfo = (String)redisRepository.get(formatKey(bearerToken)); if(spliceStaffInfo == null) { return null; } return new NamePassAuthenticationToken(new AuthStaff(spliceStaffInfo),null,AuthorityUtils.NO_AUTHORITIES); }
登錄過程
在登錄的時候,就需要用到這個自定義的認證器了
// 通過用戶名和密碼創(chuàng)建一個 Authentication 認證對象,實現類為 NamePassAuthenticationToken NamePassAuthenticationToken authenticationToken = new NamePassAuthenticationToken(user.getUsername(), user.getPassword()); //通過 AuthenticationManager(默認實現為ProviderManager)的authenticate方法驗證 Authentication 對象 //AuthenticationManager會通過你傳入的authenticationToken來找到具體的Provider Authentication authentication = authenticationManager.authenticate(authenticationToken); //填充用戶信息到secrity中的user里 User principal = (User) authentication.getPrincipal(); //獲取認證后的信息 NamePassAuthenticationToken namePassAuthenticationToken = new NamePassAuthenticationToken(new AuthStaff(principal.getUsername()), null, authentication.getAuthorities()); // 生成token String bearerToken = IdUtil.fastSimpleUUID(); // 加載到reids authRedisHelper.set(bearerToken, namePassAuthenticationToken);
這樣就實現了自定義的認證器了
到此這篇關于Spring Security自定義認證器的文章就介紹到這了,更多相關Spring Security自定義認證器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot使用yml文件配置多環(huán)境方式(dev、test、prod)
這篇文章主要介紹了springboot使用yml文件配置多環(huán)境方式(dev、test、prod),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09spring boot 自動更新靜態(tài)文件和后臺代碼的實例
下面小編就為大家分享一篇spring boot 自動更新靜態(tài)文件和后臺代碼的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12FactoryBean?BeanFactory方法使用示例詳解講解
這篇文章主要為大家介紹了FactoryBean?BeanFactory方法使用示例詳解講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12Spring Boot框架中的@Conditional注解示例詳解
這篇文章主要介紹了Spring Boot框架中的@Conditional系列注解,@ConditionalOnProperty注解的作用是解析application.yml/application.properties 里的配置生成條件來生效,也是與@Configuration注解一起使用,本文通過示例代碼給大家介紹的非常詳細,需要的朋友一起看看吧2022-09-09Spring中ApplicationContextAware的使用方法詳解
ApplicationContextAware?通過它Spring容器會自動把上下文環(huán)境對象調用ApplicationContextAware接口中的setApplicationContext方法,這篇文章主要介紹了Spring中ApplicationContextAware的作用,需要的朋友可以參考下2023-03-03