一、描述
使用springboot+spring security實現自定義登錄驗證及登錄登出結果返回
適用於前后端分離
二、處理邏輯
簡單流程
自定義UserDetails
@javax.persistence.Entity
@org.hibernate.annotations.Table(appliesTo = "local_user_details")
public class LocalUserDetails implements java.io.Serializable, UserDetails {
private static final long serialVersionUID = 1594783117560L;
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "[id]", nullable = false, unique = true, length = 0, precision = 20, scale = 0, columnDefinition = "bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵'")
@ApiModelProperty(value = "主鍵", required = false, hidden = false, example = "主鍵")
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
private Long id;
@NonNull
@Size(min = 3, max = 18)
@Column(name = "[userid]", nullable = false, unique = false, length = 64, precision = 0, scale = 0, columnDefinition = "varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用戶索引'")
@ApiModelProperty(value = "用戶索引", required = true, hidden = false, example = "用戶索引")
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
private String userid = "";
@NonNull
@Size(min = 3, max = 64)
@Column(name = "[passwd]", nullable = false, unique = false, length = 128, precision = 0, scale = 0, columnDefinition = "varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用戶密碼'")
@ApiModelProperty(value = "用戶密碼", required = true, hidden = false, example = "用戶密碼")
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
private String passwd = "";
public LocalUserDetails() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserid() {
return this.userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
//返回分配給用戶的角色列表
return new ArrayList<>();
}
@Override
public String getPassword() {
return this.getPasswd();
}
@Override
public String getUsername() {
return this.getUserid();
}
@Override
public boolean isAccountNonExpired() {
// 指定賬戶是否未過期.
return true;
}
@Override
public boolean isAccountNonLocked() {
// 指定賬戶是否未鎖定.
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// 指定密碼是否未過期.
return true;
}
@Override
public boolean isEnabled() {
// 指定用戶是否已啟用, 禁用的用戶無法進行身份驗證.
return true;
}
}
自定義UserDetailsDAO
public interface LocalUserDetailsDAO extends JpaRepository<LocalUserDetails, Long>, JpaSpecificationExecutor<LocalUserDetails> {
Optional<LocalUserDetails> findByUserid(String userid);
}
自定義UserDetailsService
@Service
@Transactional
public class AuthorityUserLoginInfoService implements UserDetailsService {
@Autowired
private LocalUserDetailsDAO dao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<LocalUserDetails> user = dao.findByUserid(username);
if (user.isPresent()) {
if (!user.get().isEnabled()) { throw new DisabledException("暫無權限!"); }
} else {
throw new UsernameNotFoundException("用戶名或密碼不正確!");
}
return user.get();
}
}
自定義用戶登錄驗證邏輯AuthenticationProvider
@Component
public class LocalAuthenticationProvider implements AuthenticationProvider {
@Autowired
private AuthorityUserLoginInfoService userService;
private final PasswordEncoder encoder = new BCryptPasswordEncoder();
/** 自定義驗證方式 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
// 獲取Request, 獲取其他參數信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attributes.getRequest().getSession();
Object others = session.getAttribute("others");
UserDetails node = userService.loadUserByUsername(username);
if (!encoder.matches(password, node.getPassword())) { throw new BadCredentialsException("用戶名或密碼不正確!"); }
return new UsernamePasswordAuthenticationToken(node, password, node.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
三、Spring Security基本配置信息
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value(value = "${ignoringAntMatchers:/**}")
private String ignoringAntMatchers;
@Value(value = "${loginPage:/login}")
private String loginPage;
@Value(value = "${loginProcessingUrl:/api/user/login}")
private String loginProcessingUrl;
@Value(value = "${logoutUrl:/api/user/logout}")
private String logoutUrl;
@Value(value = "${expiredUrl:/login}")
private String expiredUrl;
@Autowired
private DataSource dataSource;
@Autowired
private AuthorityUserLoginInfoService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(4);
}
@Bean
public AuthenticationProvider authenticationProvider() {
return new LocalAuthenticationProvider();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// 自定義用戶登錄驗證
auth.authenticationProvider(authenticationProvider());
// 指定密碼加密所使用的加密器為passwordEncoder(), 需要將密碼加密后寫入數據庫
auth.userDetailsService(this.userService).passwordEncoder(passwordEncoder());
// 不刪除憑據,以便記住用戶
auth.eraseCredentials(false);
}
@Override
public void configure(WebSecurity web) throws Exception {
// 設置不攔截規則
web.ignoring().antMatchers(this.ignoringAntMatchers.split(","));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 設置攔截規則
http.authorizeRequests().anyRequest().authenticated();
// 自定義登錄信息
http.csrf().disable().formLogin() //
.loginPage(this.loginPage) // 自定義登錄頁url,默認為/login
.loginProcessingUrl(this.loginProcessingUrl) // 登錄驗證地址, 即RequestMapping地址
// 用戶名的請求字段. 默認為org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY
.usernameParameter("username")
// 用戶名的請求字段. 默認為org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY
.passwordParameter("password") //
.successHandler(new LocalAuthenticationSuccessHandler()) // 登錄驗證成功后, 執行的內容
// .defaultSuccessUrl("/index") // 登錄驗證成功后, 跳轉的頁面, 如果自定義返回內容, 請使用successHandler方法
// .successForwardUrl("/index") // 登錄驗證成功后, 跳轉的頁面, 如果自定義返回內容, 請使用successHandler方法
.failureHandler(new LocalAuthenticationFailureHandler()) // 登錄驗證失敗后, 執行的內容
// .failureUrl("/login?error") // 登錄驗證失敗后, 跳轉的頁面, 如果自定義返回內容, 請使用failureHandler方法
.permitAll();
// 自定義異常處理器
http.exceptionHandling() // 異常處理器
// 用來解決匿名用戶訪問無權限資源時的異常
.authenticationEntryPoint(new LocalAuthenticationEntryPoint())
// 用來解決認證過的用戶訪問無權限資源時的異常, 跳轉的頁面, 如果自定義返回內容, 請使用accessDeniedHandler方法
// .accessDeniedPage("/error")
// 用來解決認證過的用戶訪問無權限資源時的異常
.accessDeniedHandler(new LocalAccessDeniedHandler());
// 自定義注銷信息
http.logout() //
.logoutUrl(this.logoutUrl) // 登出驗證地址, 即RequestMapping地址
.logoutSuccessHandler(new LocalLogoutSuccessHandler()) // 登出驗證成功后, 執行的內容
// .logoutSuccessUrl("/login?logout") // 登出驗證成功后, 跳轉的頁面, 如果自定義返回內容, 請使用logoutSuccessHandler方法
.deleteCookies("JSESSIONID") // 退出登錄后需要刪除的cookies名稱
.invalidateHttpSession(true) // 退出登錄后, 會話失效
.permitAll();
// remember-me配置
http.rememberMe() //
// org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.DEFAULT_REMEMBER_ME_NAME
.rememberMeCookieName("remember-me")
// org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.DEFAULT_REMEMBER_ME_NAME
.rememberMeParameter("remember-me")
// org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.TWO_WEEKS_S
.tokenValiditySeconds(360000)
// tokenRepository
.tokenRepository(new LocalPersistentTokenRepository(this.dataSource));
// session管理
http.sessionManagement().sessionFixation().changeSessionId() //
.maximumSessions(1) // 最大會話數
.maxSessionsPreventsLogin(false) // 達到最大數后, 強制驗證, 踢出舊用戶
// 舊用戶被踢出后, 跳轉的頁面, 如果自定義返回內容, 請使用expiredSessionStrategy方法
// .expiredUrl("/login?expired")
// 舊用戶被踢出后, 執行的內容
.expiredSessionStrategy(new LocalSessionInformationExpiredStrategy());
}
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
四、登錄登出自定義處理器
登錄成功處理器LocalAuthenticationSuccessHandler
public class LocalAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(ResultStatus.SUCCESS_LOGIN)));
}
}
登錄失敗處理器LocalAuthenticationFailureHandler
public class LocalAuthenticationFailureHandler implements AuthenticationFailureHandler {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(ResultStatus.ERROR_LOGIN)));
}
}
登出成功處理器LocalLogoutSuccessHandler
public class LocalLogoutSuccessHandler implements LogoutSuccessHandler {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(20001, "登出成功!")));
}
}
匿名用戶訪問無權限處理器LocalAuthenticationEntryPoint
public class LocalAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(ResultStatus.WRONG_DEAL)));
}
}
認證用戶訪問無權限處理器LocalAccessDeniedHandler
public class LocalAccessDeniedHandler implements AccessDeniedHandler {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
throws IOException, ServletException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(ResultStatus.WRONG_DEAL)));
}
}
舊用戶被踢處理器LocalSessionInformationExpiredStrategy
public class LocalSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
HttpServletResponse response = event.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(gson.toJson(new Result<>(20002, "用戶已退出!")));
}
}
參考文章:https://blog.csdn.net/dahaiaixiaohai/article/details/107375939