Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { String username = ((UserDetails)principal).getUsername(); } else { String username = principal.toString();
package org.springframework.security.core; import java.io.Serializable; import java.security.Principal; import java.util.Collection; public interface Authentication extends Principal, Serializable { Collection<? extends GrantedAuthority> getAuthorities(); Object getCredentials(); Object getDetails(); Object getPrincipal(); boolean isAuthenticated(); void setAuthenticated(boolean var1) throws IllegalArgumentException; }
public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean { // 維護一個AuthenticationProvider列表 private List<AuthenticationProvider> providers = Collections.emptyList(); public Authentication authenticate(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; Authentication result = null; boolean debug = logger.isDebugEnabled(); Iterator var6 = this.getProviders().iterator(); //依次來認證 while(var6.hasNext()) { AuthenticationProvider provider = (AuthenticationProvider)var6.next(); if (provider.supports(toTest)) { if (debug) { logger.debug("Authentication attempt using " + provider.getClass().getName()); } try { // 若是有Authentication信息,則直接返回 result = provider.authenticate(authentication); if (result != null) { this.copyDetails(authentication, result); break; } } catch (AccountStatusException var11) { this.prepareException(var11, authentication); throw var11; } catch (InternalAuthenticationServiceException var12) { this.prepareException(var12, authentication); throw var12; } catch (AuthenticationException var13) { lastException = var13; } } } }
5.
DaoAuthenticationProvider:它是AuthenticationProvider的的一個實現類,很是重要,它主要完成了兩個工做,protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; try { //記住loadUserByUsername這個方法; loadedUser = this.getUserDetailsService().loadUserByUsername(username); } catch (UsernameNotFoundException var6) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null); } throw var6; } catch (Exception var7) { throw new InternalAuthenticationServiceException(var7.getMessage(), var7); } if (loadedUser == null) { throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation"); } else { return loadedUser; } }
它還有一個重要的方法是
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { Object salt = null; if (this.saltSource != null) {、 //此方法在你的配置文件中去配置實現的 也是spring security加密的關鍵 ------劃重點 salt = this.saltSource.getSalt(userDetails); } if (authentication.getCredentials() == null) { this.logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { String presentedPassword = authentication.getCredentials().toString(); if (!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) { this.logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } }
這個方法的坑點仍是挺多的,主要的意思就是拿到經過用戶姓名得到的該用戶的信息(密碼等)和用戶輸入的密碼加密後對比,若是不正確就會報錯Bad credentials的錯誤。
爲何說這個方法坑,由於注意到
this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)
這裏面他自帶的一個方法用的是MD5的加密幫你加密在和你存入這個用戶時的密碼對比,
public boolean isPasswordValid(String encPass, String rawPass, Object salt) { String pass1 = encPass + ""; String pass2 = this.mergePasswordAndSalt(rawPass, salt, false); if (this.ignorePasswordCase) { pass1 = pass1.toLowerCase(Locale.ENGLISH); pass2 = pass2.toLowerCase(Locale.ENGLISH); } return PasswordEncoderUtils.equals(pass1, pass2); }
能夠注意到在生成pass2的時候傳入了salt對象,這個salt對象能夠經過配置文件去實現,也能夠本身寫一個實現類來完成。能夠說是是和用戶輸入密碼匹配的關鍵點所在。
6.UserDetails與UserDetailsService,這兩個接口在上面都出現了,先看UserDetails是什麼:
package org.springframework.security.core.userdetails; import java.io.Serializable; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; public interface UserDetails extends Serializable { Collection<? extends GrantedAuthority> getAuthorities(); String getPassword(); String getUsername(); boolean isAccountNonExpired(); boolean isAccountNonLocked(); boolean isCredentialsNonExpired(); boolean isEnabled(); }
有沒有發現它和前面的Authentication接口很像,好比它們都擁有username,authorities,區分他們也是本文的重點內容之一。
Authentication的getCredentials()與UserDetails中的getPassword()須要被區分對待,前者是用戶提交的密碼憑證,後者是用戶正確的密碼,
認證器其實就是對這二者的比對。Authentication中的getAuthorities()實際是由UserDetails的getAuthorities()傳遞而造成的。
還記得Authentication接口中的getUserDetails()方法嗎?其中的UserDetails用戶詳細信息即是通過了AuthenticationProvider以後被填充的。
public interface UserDetailsService { UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }
@Override public Collection<? extends GrantedAuthority> getAuthorities() { if(roles == null || roles.size()<=0){ return null; } List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); for(Role r:roles){ authorities.add(new SimpleGrantedAuthority(r.getRoleValue())); } return authorities; } public String getPassword() { return password; } @Override public String getUsername() { return email; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { if(StringUtils.isNotBlank(state) && "1".equals(state) && StringUtils.isNotBlank(enable) && "1".equals(enable)){ return true; } return false; } @Override public boolean equals(Object obj) { if (obj instanceof User) { return getEmail().equals(((User)obj).getEmail())||getUsername().equals(((User)obj).getUsername()); } return false; } @Override public int hashCode() { return getUsername().hashCode(); }
(1)其中 getAuthorities 方法是獲取用戶角色信息的方法,用於受權。不一樣的角色能夠擁有不一樣的權限。css
(2)帳戶未過時、帳戶未鎖定和密碼未過時咱們這裏沒有用到,直接返回 True,你也能夠根據本身的應用場景寫本身的業務邏輯。html
(3)爲了區分是不是同一個用戶,重寫 equals 和 hashCode 方法。java
由於實現接口以後能夠得到數據庫中的真是存在的信息;git
使用這個框架之間咱們要引入它,首先要在web.xml文件中引入它web
<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
而後UsernamePasswordAuthenticationFilter這個過濾器會接受到此方法,在源碼裏面已經幫咱們實現得到密碼以及用戶名的操做,而且規定post請求方法
具體代碼以下:
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (this.postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } else { String username = this.obtainUsername(request); String password = this.obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); this.setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } }
在現實生活中,開發中能夠增長的邏輯不少,因此通常都會重寫這個方法;咱們要建一個本身的類去繼承這個類:
public class AccountAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private String codeParameter = "code"; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = this.obtainUsername(request); String password = this.obtainPassword(request); String code = this.obtainCode(request); String caChecode = (String)request.getSession().getAttribute("VERCODE_KEY"); boolean flag = CodeValidate.validateCode(code,caChecode); if(!flag){ throw new UsernameNotFoundException("驗證碼錯誤"); } if(username == null) { username = ""; } if(password == null) { password = ""; } username = username.trim(); //經過構造方法實例化一個 UsernamePasswordAuthenticationToken 對象,此時調用的是 UsernamePasswordAuthenticationToken 的兩個參數的構造函數 //其中 super(null) 調用的是父類的構造方法,傳入的是權限集合,由於目前尚未認證經過,因此不知道有什麼權限信息,這裏設置爲 null,而後將用戶名和密碼分別賦值給 // principal 和 credentials,一樣由於此時還未進行身份認證,因此 setAuthenticated(false)。 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); //setDetails(request, authRequest) 是將當前的請求信息設置到 UsernamePasswordAuthenticationToken 中。 this.setDetails(request, authRequest); //經過調用 getAuthenticationManager() 來獲取 AuthenticationManager,經過調用它的 authenticate 方法來查找支持該 // token(UsernamePasswordAuthenticationToken) 認證方式的 provider,而後調用該 provider 的 authenticate 方法進行認證)。 return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(this.codeParameter); } }
裏面咱們完成了一個驗證碼的驗證工做,而且把僅爲post請求給屏蔽,獲取到用戶名和用戶密碼後,咱們把它放在了UsernamePasswordAuthenticationToken類裏,進去以後看到了
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) { super((Collection)null); this.principal = principal; this.credentials = credentials; this.setAuthenticated(false); }
代碼中給予了註釋,而後setDetails將其存入UsernamePasswordAuthenticationToken之中,而後咱們經過getAuthenticationManager()
獲取AuthenticationManager這個接口,在調用接口裏的方法,咱們繼續查找會發現AuthenticationManager這個類實現了這個接口的方法,
在方法中它又調用了AuthenticationProvide這個接口,那AuthenticationProvide這個接口的實現類是AbstractUserDetailsAuthenticationProvider
而且實現了authenticate方法,在這個方法裏面引用了兩個重要的方法additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken) authentication);
和user = retrieveUser(username,(UsernamePasswordAuthenticationToken) authentication);
那這兩個方法在子類DaoAuthenticationProvider中實現,兩個方法上面都有代碼,可是咱們再看一下其中重點的方法
protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; try { //很關鍵 loadedUser = this.getUserDetailsService().loadUserByUsername(username); } catch (UsernameNotFoundException var6) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null); } throw var6; } catch (Exception var7) { throw new InternalAuthenticationServiceException(var7.getMessage(), var7); } if (loadedUser == null) { throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation"); } else { return loadedUser; } }
那個註釋的地方是要得到一個UserDetails,上面有說到UserDetailsService常見的實現類有JdbcDaoImpl,InMemoryUserDetailsManager,爲了簡化咱們本身寫一個實現類,
由於結合咱們pojo對象實現了UserDetails的接口,因此咱們建立以下類:
public class AccountDetailsService implements UserDetailsService{ @Autowired private UserService userService; @Autowired private RoleService roleService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userService.findByEmail(username); if(user == null){ throw new UsernameNotFoundException("用戶名或密碼錯誤"); } List<Role> roles = roleService.findByUid(user.getId()); user.setRoles(roles); return user; } }
實現了loadByUsername的方法。到此爲止咱們咱們在逆向的回到了UsernamePasswordAuthenticationFilter上,且返回了一個Authentication對象。
咱們在第一個關鍵詞SecurityContextHolder中將其取出,作一些本身的業務邏輯。
工做到此尚未結束,咱們還要去受權,對認證經過的人去受權,這裏咱們能夠xml去配置這些信息:咱們前面留了一個問題就是salt加密密碼驗證,咱們前面還不知道salt
對象是什麼,因此須要配置一下
<!-- 認證管理器,使用自定義的accountService,並對密碼採用md5加密 --> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="accountService"> <security:password-encoder hash="md5"> <security:salt-source user-property="username"></security:salt-source> </security:password-encoder> </security:authentication-provider> </security:authentication-manager>
其實salt能夠本身代碼去配置,經過這個xml去配置也行,最緊要的仍是要和你原來數據庫密碼的加密方式有關係,我這裏是用了pojo對象裏的用戶名做爲salt對象,
因此個人密碼加密方式就是username+password再用MD5加密了。那還有一個重要的工做就是受權配置
<security:http security="none" pattern="/css/**" /> <security:http security="none" pattern="/js/**" /> <security:http security="none" pattern="/images/**" /> <security:intercept-url pattern="/" access="permitAll"/> <security:intercept-url pattern="/index**" access="permitAll"/> <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
這些都是基礎的一些受權操做,還有配置在咱們的AccountAuthenticationFilter類中是否是經過了驗證
<bean id="authenticationFilter" class="***.***.**.**.AccountAuthenticationFilter"> <property name="filterProcessesUrl" value="/doLogin"></property> <property name="authenticationManager" ref="authenticationManager"></property> <property name="sessionAuthenticationStrategy" ref="sessionStrategy"></property> <property name="authenticationSuccessHandler"> <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/list"></property> </bean> </property> <property name="authenticationFailureHandler"> <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/login.jsp?error=fail"></property> </bean> </property> </bean>
其中defaultTargetUrl和defaultFailureUrl是經過和不經過的一些採起措施,一般是一些頁面跳轉。
其他的配置文件信息,我尚未琢磨透,之後有時間在發表一篇。
最後:用一張圖大體的總結下它的具體流程(本圖來自王林永老師的gitchat):
https://www.cnblogs.com/zahfyy/p/9720124.htmlspring