Spring Boot+Spring Security+Ajax to achieve custom login
Custom users need to implement the UserDetails interface. The Security framework doesn’t care how your application stores user and permission information. Just wrap it as a UserDetails object when you pull it out. :
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;
}
// Assign the administrator role directly without involving the user role
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_ADMIN");
return auths;
}
// Whether the account is expired
@Override
public boolean isAccountNonExpired(a) {
return true;
}
// Whether the account is locked
@Override
public boolean isAccountNonLocked(a) {
return true;
}
// Whether the password has expired
@Override
public boolean isCredentialsNonExpired(a) {
return true;
}
// Whether it is available
@Override
public boolean isEnabled(a) {
return true; }}Copy the code
The UserDetailsService interface is used to loadUser information. Then, in the loadUserByUsername method, a User object is constructed to return. This interface is implemented here to define its own 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);// Query the database to see if the user exists
// ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletRequestAttributes.getRequest();
// request.setAttribute("username",s);
if (user == null) {throw new ValidateCodeException("User does not exist");
}
// LockUser lockUser = lockUserMapper.findLockUserById(user.getId());
// log.info("{}",lockUser);
// if ( lockUser ! = null) {
// // throw new LockedException("LOCK");
// user.setCheckLockIsOrNot(false);
/ /}
returnuser; }}Copy the code
The core configuration classes for Spring Security:
Because you focus only on login authentication, the other features are commented out first.
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 core configuration class ** /
@Configuration// Identifies the configuration class
@EnableWebSecurity// Start Security management for 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(a){// Password encryption class
return new BCryptPasswordEncoder();
}
@Bean
public MyUserDetailService myUserDetailService(a){
return new MyUserDetailService();
}
// @Bean
// public PersistentTokenRepository persistentTokenRepository() {
// JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
// // Configuring a data source
// jdbcTokenRepository.setDataSource(dataSource);
// // the first time to start the automatic build table (can not use this sentence, their own manual build table, source code has a statement)
// // jdbcTokenRepository.setCreateTableOnStartup(true);
// return jdbcTokenRepository;
/ /}
@Autowired
private UserLoginAuthenticationFailureHandler userLoginAuthenticationFailureHandler;// Validate failed handler class
@Autowired
private UserLoginAuthenticationSuccessHandler userLoginAuthenticationSuccessHandler;// Verify the successful processing class
// @Autowired
// private UserLogoutSuccessHandler userLogoutSuccessHandler;
// @Autowired
// private UserAuthenticationAccessDeniedHandler userAuthenticationAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
// ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
// http
// .headers().frameOptions().sameOrigin(); // Set the pop-up layer
// http
// .authorizeRequests()
// .and()
// .rememberMe()
// .tokenRepository(persistentTokenRepository())
// .userDetailsService(myUserDetailService());;
http
.authorizeRequests()
// .antMatchers("/admin/**","/setUserAdmin","/setUser","/deleteUserById")
//.access("hasRole('ROLE_ADMIN')")// Only administrators can access it
.antMatchers("/home"."/static/**"."/getAllUser"."/register_page"."/register"."/checkNameIsExistOrNot"."/code/image")// Static resources and so on do not need validation
.permitAll()// No authentication is required
.anyRequest().authenticated();// Other paths must authenticate
http
.formLogin()
.loginPage("/login_page")// Login page, load the login HTML page
.loginProcessingUrl("/login")// Path to send the Ajax request
.usernameParameter("username")// Request validation parameters
.passwordParameter("password")// Request validation parameters
.failureHandler(userLoginAuthenticationFailureHandler)// Verification failed processing
.successHandler(userLoginAuthenticationSuccessHandler)// Verify successful processing
.permitAll();// No authentication is required for the login page
// .and()
// .rememberMe()
// .tokenRepository(persistentTokenRepository())
// // failure time
// .tokenValiditySeconds(3600)
// .userDetailsService(myUserDetailService());
// http
// .logout()
//. LogoutSuccessHandler (userLogoutSuccessHandler)// Logout processing
// .permitAll()
// .and()
// .csrf().disable()
// .exceptionHandling().accessDeniedHandler(userAuthenticationAccessDeniedHandler); // Do not have the right to limit the processing
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailService()).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return ENCODER.encode(charSequence);
}
// The password matches to see if the entered password is encrypted and stored in the database
@Override
public boolean matches(CharSequence charSequence, String s) {
returnENCODER.matches(charSequence,s); }}); }}Copy the code
Define what happens when authentication succeeds and fails:
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. ** User authentication successfully handled class */
@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."Certification 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(); }}Copy the code
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. ** User authentication failure handler */
@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("{}"," authentication failed ");
// log.info("{}",exception.getMessage());
// String username = (String) request.getAttribute("username");
JsonData jsonData = null;
if (exception.getMessage().equals("User does not exist")){
jsonData = new JsonData(402."User does not exist");
}
if(exception.getMessage().equals("Bad credentials")){
jsonData = new JsonData(403."Password error");
// 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," password error, you have 2 more chances to log in ");
// }
// else if(userService.getAttempts(username) == 3){
// User user = userService.findByUserName(username);
// userService.LockUser(user.getId());
// jsonData = new jsonData (403," The last attempt to log in failed, you have been frozen ");
// }
// else if (userService.getAttempts(username) ==2 ){
// String time = DateUtil.getTimeToString();
// userService.setAttempts(username,time);
// jsonData = new jsonData (403," password error, you have 1 more chance to login ");
// }
}
// if (exception.getMessage().equals("User account is locked")){
// jsonData = new JsonData(100,"LOCK");
// }
String json = new Gson().toJson(jsonData);// Wrap as Json to send foreground
response.setContentType("application/json; charset=utf-8"); PrintWriter out = response.getWriter(); out.write(json); out.flush(); out.close(); }}Copy the code
The foreground page uses LayUI
Login page:
/** * Created by linziyu on 2019/2/9. */
// Login processing
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".// Request path
data:{
"username": username,// The field must be the same as the HTML page id and name
"password": password,// The field should correspond to the HTML page
// "remember-me":remember,
// "imageCode": imageCode
},
dataType:"json".type:'post'.async:false.success:function (data) {
if (data.code == 402){
layer.alert("User name does not exist".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(" The user has been frozen, please contact the administrator to unfreeze ",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"
/ /});
// }}}); })});Copy the code
Why is about Ajax request path “/ login” can see the source code UsernamePasswordAuthenticationFilter class this Spring Security the Filter You can see that the first Filter executed in line 26 has a default setting
//
// 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(a) {
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(a) {
return this.usernameParameter;
}
public final String getPasswordParameter(a) {
return this.passwordParameter; }}Copy the code
Database operation is not wordy, using Mybatis+Mysql combination, nothing more than CRUD.
Specific demo on my github: github.com/LinZiYU1996…