实现json登录的过程中遇到太多的坑了,很多配置项自定义之后会导致其他配置项失效,
临时放弃json登录,使用推荐的form表单登录的方式。
json登录参考:Spring Boot 2.x 集成Spring Security,前后端分离,json登录,json响应
项目源码:https://github.com/dk980241/spring-boot-security-demo
site.yuyanjia.springbootsecuritydemo.config.FormWebSecurityConfig
主配置
实现框架的 WebSecurityConfigurerAdapter
FormWebSecurityConfig.java
package site.yuyanjia.springbootsecuritydemo.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.access.vote.UnanimousBased;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.config.annotation.web.configurers.RememberMeConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.expression.WebExpressionVoter;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import site.yuyanjia.springbootsecuritydemo.dao.WebUserDao;
import site.yuyanjia.springbootsecuritydemo.security.WebUserDetail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 默认安全配置
*
* form表单
*
* @author seer
* @date 2019/7/21 9:30
*/
@Configuration
@EnableWebSecurity
@SuppressWarnings("all")
public class FormWebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(FormWebSecurityConfig.class);
/**
* 成功
*/
private static final String SUCCESS = "{\"result_code\": \"00000\", \"result_msg\": \"处理成功\"}";
/**
* 失败
*/
private static final String FAILED = "{\"result_code\": \"99999\", \"result_msg\": \"处理失败\"}";
/**
* 登录过期
*/
private static final String LOGIN_EXPIRE = "{\"result_code\": \"10001\", \"result_msg\": \"登录过期\"}";
/**
* 权限限制
*/
private static final String ROLE_LIMIT = "{\"result_code\": \"10002\", \"result_msg\": \"权限不足\"}";
/**
* 登录 URL
*/
private static final String LOGIN_URL = "/authc/login";
/**
* 登出 URL
*/
private static final String LOGOUT_URL = "/authc/logout";
/**
* 授权 URL
*/
private static final String AUTH_URL_REG = "/authc/**";
/**
* 登录用户名参数名
*/
private static final String LOGIN_NAME = "username";
/**
* 登录密码参数名
*/
private static final String LOGIN_PWD = "password";
/**
* 记住登录参数名
*/
private static final String REMEMBER_ME = "rememberMe";
/**
* token有效时间10天
* 框架实现 {@link RememberMeConfigurer#tokenValiditySeconds}
* 此处使用redis实现
*/
private static final Long TOKEN_VALID_DAYS = 10L;
@Autowired
private UserDetailsService webUserDetailsService;
@Autowired
private WebUserDao webUserDao;
@Autowired
private RedisTemplate redisTemplate;
/**
* cors跨域
*
* @return
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
corsConfiguration.addExposedHeader("access-control-allow-methods");
corsConfiguration.addExposedHeader("access-control-allow-headers");
corsConfiguration.addExposedHeader("access-control-allow-origin");
corsConfiguration.addExposedHeader("access-control-max-age");
corsConfiguration.addExposedHeader("X-Frame-Options");
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration(AUTH_URL_REG, corsConfiguration);
return configurationSource;
}
/**
* http安全配置
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable();
http
.exceptionHandling()
.accessDeniedHandler(new DefinedAccessDeniedHandler())
.authenticationEntryPoint(new DefinedAuthenticationEntryPoint());
http
.authorizeRequests()
.accessDecisionManager(accessDecisionManager())
.withObjectPostProcessor(new DefindeObjectPostProcessor());
http
.authorizeRequests()
.antMatchers(AUTH_URL_REG).authenticated()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().permitAll();
http
.formLogin()
.usernameParameter(LOGIN_NAME)
.passwordParameter(LOGIN_PWD)
.loginProcessingUrl(LOGIN_URL)
.successHandler(new DefinedAuthenticationSuccessHandler())
.failureHandler(new DefindeAuthenticationFailureHandler());
http
.logout()
.logoutUrl(LOGOUT_URL)
.invalidateHttpSession(true)
.invalidateHttpSession(true)
.logoutSuccessHandler(new DefinedLogoutSuccessHandler());
http
.rememberMe()
.rememberMeParameter(REMEMBER_ME)
.tokenRepository(new RedisTokenRepositoryImpl());
}
/**
* 配置登录验证
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(webUserDetailsService);
auth.authenticationProvider(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String loginUsername = authentication.getName();
String loginPassword = (String) authentication.getCredentials();
log.info("用户登录,用户名 [{}],密码 [{}]", loginUsername, loginPassword);
WebUserDetail webUserDetail = (WebUserDetail) webUserDetailsService.loadUserByUsername(loginUsername);
// 此处自定义密码加密处理规则
if (!loginPassword.equals(webUserDetail.getPassword())) {
throw new DisabledException("用户登录,密码错误");
}
return new UsernamePasswordAuthenticationToken(webUserDetail, webUserDetail.getPassword(), webUserDetail.getAuthorities());
}
/**
* 支持使用此方法验证
*
* @param aClass
* @return 没有特殊处理,返回true,否则不会用这个配置进行验证
*/
@Override
public boolean supports(Class> aClass) {
return true;
}
});
}
/**
* 决策管理
*
* @return
*/
private AccessDecisionManager accessDecisionManager() {
List> decisionVoters = new ArrayList<>();
decisionVoters.add(new WebExpressionVoter());
decisionVoters.add(new AuthenticatedVoter());
decisionVoters.add(new RoleVoter());
decisionVoters.add(new UrlRoleVoter());
UnanimousBased based = new UnanimousBased(decisionVoters);
return based;
}
class DefindeObjectPostProcessor implements ObjectPostProcessor {
@Override
public O postProcess(O object) {
object.setSecurityMetadataSource(new DefinedFilterInvocationSecurityMetadataSource());
return object;
}
}
/**
* {@link org.springframework.security.access.vote.RoleVoter}
*/
class UrlRoleVoter implements AccessDecisionVoter
用户信息获取
实现框架默认的 UserDetailsService
WebUserDetailsServiceImpl.java
package site.yuyanjia.springbootsecuritydemo.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import site.yuyanjia.springbootsecuritydemo.dao.WebUserDao;
import site.yuyanjia.springbootsecuritydemo.model.WebUserDO;
import java.util.Set;
/**
* 用户信息获取service
*
* @author seer
* @date 2018/12/3 14:46
*/
@Service("webUserDetailsService")
public class WebUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private WebUserDao webUserDao;
/**
* 根据用户名登录
*
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
WebUserDO webUserDO = webUserDao.getUserByUsername(username);
if (null == webUserDO) {
throw new UsernameNotFoundException("用户登录,用户信息查询失败");
}
Set roleSet = webUserDao.listRoleByUserId(webUserDO.getId());
/**
封装为框架使用的 userDetail {@link UserDetails}
*/
WebUserDetail webUserDetail = new WebUserDetail(webUserDO);
webUserDetail.setRoleSet(roleSet);
return webUserDetail;
}
}