Spring Boot+Spring Security+Ajax 實(shí)現(xiàn)自定義登錄
自定義的用戶需要實(shí)現(xiàn)UserDetails接口,Security這個(gè)框架不關(guān)心你的應(yīng)用時(shí)怎么存儲(chǔ)用戶和權(quán)限信息的。只要取出來的時(shí)候把它包裝成一個(gè)UserDetails對(duì)象就OK。:
User.class:
package com.example.demo.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class User implements UserDetails{
private Integer id;
private String username;
private String password;
private List<Role> roles;
// private String role;
// private String status;
// private boolean checkLockIsOrNot=true;
public User(String username,String password){
this.username = username;
this.password = password;
}
//不涉及用戶角色,直接賦予管理員角色
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_ADMIN");
return auths;
}
//賬戶是否過期
@Override
public boolean isAccountNonExpired() {
return true;
}
//賬戶是否鎖定
@Override
public boolean isAccountNonLocked() {
return true;
}
//密碼是否過期
@Override
public boolean isCredentialsNonExpired() {
return true;
}
//是否可用
@Override
public boolean isEnabled() {
return true;
}
}
UserDetailsService接口用來加載用戶信息,然后在loadUserByUsername方法中,構(gòu)造一個(gè)User對(duì)象返回,這里實(shí)現(xiàn)這個(gè)接口來定義自己的Service
MyUserDetailService.class:
package com.example.demo.service;
import com.example.demo.exception.ValidateCodeException;
import com.example.demo.mapper.LockUserMapper;
import com.example.demo.model.LockUser;
import com.example.demo.model.User;
import com.example.demo.model.UserLoginAttempts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* Created by linziyu on 2019/2/9.
*
*
*/
@Component("MyUserDetailService")
@Slf4j
public class MyUserDetailService implements UserDetailsService{
@Autowired
private UserService userService;
// @Autowired
// private LockUserMapper lockUserMapper;
// private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
// List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
// grantedAuthorityList.add(new GrantedAuthority() {
// @Override
// public String getAuthority() {
// return "admin";
// }
// });
User user = userService.findByUserName(s);//數(shù)據(jù)庫查詢 看用戶是否存在
// ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletRequestAttributes.getRequest();
// request.setAttribute("username",s);
if (user == null){
throw new ValidateCodeException("用戶不存在");
}
// LockUser lockUser = lockUserMapper.findLockUserById(user.getId());
// log.info("{}",lockUser);
// if ( lockUser != null) {
// // throw new LockedException("LOCK");
// user.setCheckLockIsOrNot(false);
// }
return user;
}
}
Spring Security的核心配置類:
因?yàn)橹痪劢沟卿涷?yàn)證這個(gè)操作,其它功能就先注釋掉了。
BrowerSecurityConfig.class:
package com.example.demo.config;
import com.example.demo.filter.ValidateCodeFilter;
import com.example.demo.handle.UserAuthenticationAccessDeniedHandler;
import com.example.demo.handle.UserLoginAuthenticationFailureHandler;
import com.example.demo.handle.UserLoginAuthenticationSuccessHandler;
import com.example.demo.handle.UserLogoutSuccessHandler;
import com.example.demo.service.MyUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* Created by linziyu on 2019/2/8.
*
*Spirng Security 核心配置類
*
*/
@Configuration//標(biāo)識(shí)為配置類
@EnableWebSecurity//啟動(dòng)Spring Security的安全管理
// @EnableGlobalMethodSecurity(securedEnabled = true)
// @Slf4j
public class BrowerSecurityConfig extends WebSecurityConfigurerAdapter {
private final static BCryptPasswordEncoder ENCODER = new BCryptPasswordEncoder();
// @Resource(name = "dataSource")
// DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder(){//密碼加密類
return new BCryptPasswordEncoder();
}
@Bean
public MyUserDetailService myUserDetailService(){
return new MyUserDetailService();
}
// @Bean
// public PersistentTokenRepository persistentTokenRepository() {
// JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
// // 配置數(shù)據(jù)源
// jdbcTokenRepository.setDataSource(dataSource);
// // 第一次啟動(dòng)的時(shí)候自動(dòng)建表(可以不用這句話,自己手動(dòng)建表,源碼中有語句的)
// // jdbcTokenRepository.setCreateTableOnStartup(true);
// return jdbcTokenRepository;
// }
@Autowired
private UserLoginAuthenticationFailureHandler userLoginAuthenticationFailureHandler;//驗(yàn)證失敗的處理類
@Autowired
private UserLoginAuthenticationSuccessHandler userLoginAuthenticationSuccessHandler;//驗(yàn)證成功的處理類
// @Autowired
// private UserLogoutSuccessHandler userLogoutSuccessHandler;
// @Autowired
// private UserAuthenticationAccessDeniedHandler userAuthenticationAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
// ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
// http
// .headers().frameOptions().sameOrigin();//設(shè)置彈出層
// http
// .authorizeRequests()
// .and()
// .rememberMe()
// .tokenRepository(persistentTokenRepository())
// .userDetailsService(myUserDetailService());;
http
.authorizeRequests()
// .antMatchers("/admin/**","/setUserAdmin","/setUser","/deleteUserById")
// .access("hasRole('ROLE_ADMIN')")//只有管理員才能訪問
.antMatchers("/home","/static/**","/getAllUser","/register_page",
"/register","/checkNameIsExistOrNot","/code/image")//靜態(tài)資源等不需要驗(yàn)證
.permitAll()//不需要身份認(rèn)證
.anyRequest().authenticated();//其他路徑必須驗(yàn)證身份
http
.formLogin()
.loginPage("/login_page")//登錄頁面,加載登錄的html頁面
.loginProcessingUrl("/login")//發(fā)送Ajax請(qǐng)求的路徑
.usernameParameter("username")//請(qǐng)求驗(yàn)證參數(shù)
.passwordParameter("password")//請(qǐng)求驗(yàn)證參數(shù)
.failureHandler(userLoginAuthenticationFailureHandler)//驗(yàn)證失敗處理
.successHandler(userLoginAuthenticationSuccessHandler)//驗(yàn)證成功處理
.permitAll();//登錄頁面無需設(shè)置驗(yàn)證
// .and()
// .rememberMe()
// .tokenRepository(persistentTokenRepository())
// // 失效時(shí)間
// .tokenValiditySeconds(3600)
// .userDetailsService(myUserDetailService());
// http
// .logout()
// .logoutSuccessHandler(userLogoutSuccessHandler)//登出處理
// .permitAll()
// .and()
// .csrf().disable()
// .exceptionHandling().accessDeniedHandler(userAuthenticationAccessDeniedHandler);//無權(quán)限時(shí)的處理
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailService()).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return ENCODER.encode(charSequence);
}
//密碼匹配,看輸入的密碼經(jīng)過加密與數(shù)據(jù)庫中存放的是否一樣
@Override
public boolean matches(CharSequence charSequence, String s) {
return ENCODER.matches(charSequence,s);
}
});
}
}
定義認(rèn)證成功和失敗時(shí)候的處理:
UserLoginAuthenticationSuccessHandler.class:
package com.example.demo.handle;
import com.example.demo.common.JsonData;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by linziyu on 2019/2/9.
*
* 用戶認(rèn)證成功處理類
*/
@Component("UserLoginAuthenticationSuccessHandler")
@Slf4j
public class UserLoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
JsonData jsonData = new JsonData(200,"認(rèn)證OK");
String json = new Gson().toJson(jsonData);
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(json);
out.flush();
out.close();
}
}
UserLoginAuthenticationFailureHandler.class:
package com.example.demo.handle;
import com.example.demo.common.DateUtil;
import com.example.demo.common.JsonData;
import com.example.demo.model.User;
import com.example.demo.model.UserLoginAttempts;
import com.example.demo.service.UserService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by linziyu on 2019/2/9.
*
* 用戶認(rèn)證失敗處理類
*/
@Component("UserLoginAuthenticationFailureHandler")
@Slf4j
public class UserLoginAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Resource
private UserService userService;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
// log.info("{}","認(rèn)證失敗");
// log.info("{}",exception.getMessage());
// String username = (String) request.getAttribute("username");
JsonData jsonData = null;
if (exception.getMessage().equals("用戶不存在")){
jsonData = new JsonData(402,"用戶不存在");
}
if(exception.getMessage().equals("Bad credentials")){
jsonData = new JsonData(403,"密碼錯(cuò)誤");
// String user_name =userService.findByUserNameAttemps(username);
// if (user_name == null){
// String time = DateUtil.getTimeToString();
// UserLoginAttempts userLoginAttempts = new UserLoginAttempts(username,1,time);
// userService.saveAttempts(userLoginAttempts);
// }
// if(userService.getAttempts(username) == 1){
// String time = DateUtil.getTimeToString();
// userService.setAttempts(username,time);
// jsonData = new JsonData(403,"密碼錯(cuò)誤,你還有2次機(jī)會(huì)進(jìn)行登錄操作");
// }
// else if(userService.getAttempts(username) == 3){
// User user = userService.findByUserName(username);
// userService.LockUser(user.getId());
// jsonData = new JsonData(403,"最后一次嘗試登陸失敗,你已經(jīng)被凍結(jié)了");
// }
// else if (userService.getAttempts(username) ==2 ){
// String time = DateUtil.getTimeToString();
// userService.setAttempts(username,time);
// jsonData = new JsonData(403,"密碼錯(cuò)誤,你還有1次機(jī)會(huì)進(jìn)行登錄操作");
// }
}
// if (exception.getMessage().equals("User account is locked")){
// jsonData = new JsonData(100,"LOCK");
// }
String json = new Gson().toJson(jsonData);//包裝成Json 發(fā)送的前臺(tái)
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(json);
out.flush();
out.close();
}
}
前臺(tái)頁面使用的是LayUI
登錄頁面:x1.PNG
用戶不存在:
d1.PNG
密碼錯(cuò)誤:
到.PNG
核心在login.js:
/**
* Created by linziyu on 2019/2/9.
*/
// 登錄處理
layui.use(['form','layer','jquery'], function () {
var form = layui.form;
var $ = layui.jquery;
form.on('submit(login)',function (data) {
var username = $('#username').val();
var password = $('#password').val();
var remember = $('input:checkbox:checked').val();
var imageCode = $('#imgcode').val();
$.ajax({
url:"/login",//請(qǐng)求路徑
data:{
"username": username,//字段和html頁面的要對(duì)應(yīng) id和name一致
"password": password,//字段和html頁面的要對(duì)應(yīng)
// "remember-me":remember,
// "imageCode": imageCode
},
dataType:"json",
type:'post',
async:false,
success:function (data) {
if (data.code == 402){
layer.alert("用戶名不存在",function () {
window.location.href = "/login_page"
});
}
if (data.code == 403){
layer.alert(data.msg,function () {
window.location.href = "/login_page"
});
}
// if (data.code == 100){
// layer.alert("該用戶已經(jīng)被凍結(jié),請(qǐng)聯(lián)系管理員進(jìn)行解凍",function () {
// window.location.href = "/login_page"
// });
// }
if(data.code == 200){
window.location.href = "/";
}
// if (data.code == 101){
// layer.alert(data.msg,function () {
// window.location.href = "/login_page"
// });
// }
}
});
})
});
關(guān)于Ajax請(qǐng)求路徑為什么是”/login“可以看源碼UsernamePasswordAuthenticationFilter.class這是Spring Security Filter 中的第一個(gè)進(jìn)行執(zhí)行的Filter可以看到在第26行有默認(rèn)的設(shè)置
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.security.web.authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
private String usernameParameter = "username";
private String passwordParameter = "password";
private boolean postOnly = true;
public UsernamePasswordAuthenticationFilter() {
super(new AntPathRequestMatcher("/login", "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);
}
}
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(this.passwordParameter);
}
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(this.usernameParameter);
}
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
public void setUsernameParameter(String usernameParameter) {
Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
this.usernameParameter = usernameParameter;
}
public void setPasswordParameter(String passwordParameter) {
Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
this.passwordParameter = passwordParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return this.usernameParameter;
}
public final String getPasswordParameter() {
return this.passwordParameter;
}
}
數(shù)據(jù)庫操作就不啰嗦了,用的是Mybatis+Mysql組合,無非是CRUD了。
具體demo在我的github:
https://github.com/LinZiYU1996/Spring-Boot-Mybatis-springsecurity