springbootsecurity安全机制
springboot security 安全机制
认证流程:
1、由认证配置WebSecurityConfigurerAdapter的configure(HttpSecurity http)⽅法进⼊,添加addFilterBefore
2、进⼊AbstractAuthenticationProcessingFilter的attemptAuthentication⽅法,指定认证对象AbstractAuthenticationToken
3、进⼊认证逻辑AuthenticationProvider,根据supports的断定对认证的⽬标对象指定对哪个进⾏认证,进⼊具体的认证逻辑⽅法authenticate
4、认证结果:认证成功后进⼊的successfulAuthentication⽅法;认证失败后进⼊的unsuccessfulAuthentication⽅法
5、对认证结果进⾏处理
a.认证成功的逻辑:进⼊SimpleUrlAuthenticationSuccessHandler的onAuthenticationSuccess⽅法
b.认证失败的逻辑:进⼊SimpleUrlAuthenticationFailureHandler的onAuthenticationFailure⽅法
6、返回结果给页⾯,将数据封装在ObjectMapper对象中,将会以⽂本形式返回给客户端(页⾯)
代码块
⾃定义认证配置,实现WebSecurityConfigurerAdapter
fig;
avelsky.auto.login.BeforeLoginFilter;
avelsky.auto.login.LoginProvider;
avelsky.auto.login.OnFailureLogin;
ken.OnFailureToken;
ken.TokenFilter;
ken.TokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Configuration;
import org.fig.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.fig.annotation.web.builders.HttpSecurity;
import org.fig.figuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* 认证配置
*/
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
/**
* 认证成功处理
*/
@Autowired
private SimpleUrlAuthenticationSuccessHandler successHandler;
/**
* 登录认证失败后处理
*/
@Autowired
private OnFailureLogin failureHandler;
/**
* token认证失败后处理
*/
@Autowired
private OnFailureToken onFailureToken;
/**
* 登录认证逻辑
*/
@Autowired
private LoginProvider loginProvider;
/**
* token认证逻辑
*/
@Autowired
private TokenProvider tokenProvider;
/**
* 配置请求权限
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 允许登录路径通过
.antMatchers("/login").permitAll()
// 允许业务路径通过
.antMatchers("/**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.
authenticated()
.and()
.csrf().disable()
// 添加
.addFilterBefore(getLoginFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(getTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
/**
* 登录
* @return
* @throws Exception
*/
private AbstractAuthenticationProcessingFilter getLoginFilter() throws Exception {
BeforeLoginFilter beforeLoginFilter = new BeforeLoginFilter("/login", successHandler, failureHandler);
beforeLoginFilter.setAuthenticationManager(super.authenticationManager());
return beforeLoginFilter;
}
/**
* token
* @return
* @throws Exception
*/
private AbstractAuthenticationProcessingFilter getTokenFilter() throws Exception {
TokenFilter tokenFilter = new TokenFilter("/**", onFailureToken);
tokenFilter.setAuthenticationManager(super.authenticationManager());
return tokenFilter;
}
/**
* 配置认证逻辑列表,按顺序进⾏认证
* @param auth
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(loginProvider);
auth.authenticationProvider(tokenProvider);
}
}
⾃定义,继承AbstractAuthenticationProcessingFilter
avelsky.auto.login;
slf4j.Slf4j;
import org.Authentication;
import org.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 登录⾃定义,继承AbstractAuthenticationProcessingFilter
*/
@Slf4j
public class BeforeLoginFilter extends AbstractAuthenticationProcessingFilter {
/
**
*认证成功的处理对象
*/
private AuthenticationSuccessHandler successHandler;
/**
* 认证失败的处理对象
*/
private AuthenticationFailureHandler failureHandler;
public BeforeLoginFilter(String defaultFilterProcessesUrl, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
super(defaultFilterProcessesUrl);
this.successHandler = successHandler;
this.failureHandler = failureHandler;
}
/**
* 过滤器处理逻辑
* @param request
* @param response
* @return
* @throws AuthenticationException
* @throws IOException
* @throws ServletException
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
log.info("进⼊登录过滤器");
String userName = Parameter("userName");
String password = Parameter("password");
LoginInfo loginInfo = new LoginInfo(null, userName, password);
log.info("username = {}", userName);
log.info("password = {}", password);
// 返回指定的认证对象
LoginAuthenticationToken loginAuthentication = new LoginAuthenticationToken(null, loginInfo, null);
// 将来由认证逻辑AuthenticationProvider来处理,这⾥返回LoginAuthenticationToken对象,将来由AuthenticationProvider的supports⽅法相匹配的认证逻辑来处理
AuthenticationManager().authenticate(loginAuthentication);
}
/**
* 认证逻辑认证成功成功后会调⽤此⽅法
* @param request
* @param response
* @param chain
* @param authResult
* @throws IOException
* @throws ServletException
*/
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { AuthenticationSuccess(request, response, authResult);
}
/**
* 认证逻辑认证失败后调⽤此⽅法
* @param request
* @param response
* @param failed
* @throws IOException
* @throws ServletException
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
}
}
⾃定义认证逻辑,继承AuthenticationProvider
avelsky.auto.login;
import com.alibaba.fastjson.JSONObject;
avelsky.pojo.MenuVO;
avelsky.pojo.SysUserInfo;
avelsky.service.SysUserInfoService;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.Authentication;
import org.AuthenticationException;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 认证逻辑
*/
@Component
@Slf4j
public class LoginProvider implements AuthenticationProvider {
@Autowired
private SysUserInfoService userInfoService;
/**
* 认证逻辑,认证的⽬标对象由supports断定,supports断定的⽬标对象是LoginAuthenticationToken⾃定义认证对象
* @param authentication
* @return
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
log.info("登录验证器,接收参数:{}", JSONString(authentication));
// Authentication的具体⼦类,可由supports断定,supports断定⼦类是LoginAuthenticationToken,因此可以强转
final LoginAuthenticationToken loginAuthentication = (LoginAuthenticationToken) authentication;
final LoginInfo loginInfo = LoginInfo();
final String userName = UserName();
final SysUserInfo userInfo = ByUserId(userName);
if (Password().Password())) {
final List<MenuVO> userInfoMenus = Id());
springboot和过滤器return new LoginAuthenticationToken(null, loginInfo, userInfoMenus);
} else {
<("登录验证失败");
throw new AuthenticationServiceException("登录失败.........");
}
}
* 指定对谁进⾏认证,这⾥指定对LoginAuthenticationToken⾃定义认证对象进⾏认证
* @param authentication
* @return
*/
@Override
public boolean supports(Class<?> authentication) {
return LoginAuthenticationToken.class.isAssignableFrom(authentication);
}
}
⾃定义认证成功的处理逻辑,继承SimpleUrlAuthenticationSuccessHandler
avelsky.auto.login;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
ken.TokenContent;
ken.TokenFactory;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.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;
/**
* ⾃定义认证成功处理逻辑,继承SimpleUrlAuthenticationSuccessHandler类
*/
@Component
@Slf4j
public class OnSuccessfulLogin extends SimpleUrlAuthenticationSuccessHandler {
/**
* 返回页⾯的对象,可将对象转化为⽂本形式(json格式)
*/
@Autowired
private ObjectMapper objectMapper;
/**
* token⼯⼚
*/
@Autowired
private TokenFactory tokenFactory;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info("登录认证成功,传⼊参数:{}", JSONString(authentication));
// 配置响应编码格式为UTF-8
response.setCharacterEncoding("UTF-8");
// 配置返回格式为json
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
// Authentication的具体⼦类为LoginAuthenticationToken
final LoginAuthenticationToken loginAuthenticationToken = (LoginAuthenticationToken) authentication;
final TokenContent tokenContent = ateToken("token");
JSONObject json = new JSONObject();
json.put("code", "000000");
json.put("message", "认证成功");
json.put("claims", Claims());
json.put("token", Token());
json.put("menuList", UserInfoMenus());
log.info("⽣产token:{}",Token());
// 将数据保存到objectMapper中,将会转化为⽂本格式,返回给页⾯
objectMapper.Writer(), json);
}
}
⾃定义认证失败逻辑,继承SimpleUrlAuthenticationFailureHandler
avelsky.auto.login;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class OnFailureLogin extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
log.info("登录认证失败,传⼊参数:{}", JSONString(exception));
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
JSONObject json = new JSONObject();
json.put("code", "999999");
json.put("message", Message());
objectMapper.Writer(), json);
}
}
⾃定义认证对象,继承AbstractAuthenticationToken
avelsky.auto.login;
avelsky.pojo.MenuVO;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.GrantedAuthority;
import java.util.Collection;
import java.util.List;
/**
* ⾃定义登录认证对象
*/
public class LoginAuthenticationToken extends AbstractAuthenticationToken {
/**
* 登录数据对象
*/
private LoginInfo loginInfo;
/**
* 菜单数据对象
*/
private List<MenuVO> userInfoMenus;
LoginAuthenticationToken(Collection<? extends GrantedAuthority> authorities, LoginInfo loginInfo, List<MenuVO> userInfoMenus) {
super(authorities);
this.userInfoMenus = userInfoMenus;
this.loginInfo = loginInfo;
}
@Override
public Object getCredentials() {
Password();
}
@Override
public Object getPrincipal() {
UserName();
}
public LoginInfo getLoginInfo() {
return loginInfo;
}
public List<MenuVO> getUserInfoMenus() {
return userInfoMenus;
}
}
⾃定义:继承AbstractAuthenticationProcessingFilter,重写attemptAuthentication(HttpServletRequest request, HttpServletResponse response) ⽅法,返回AbstractAuthenticationToken的⼦类,AbstractAuthenticationToken的⼦类可⾃⼰定义内容(例如:⽤户信息,token字符串,Claims),只要继承AbstractAuthenticationToken即可
⾃定义验证规则:实现AuthenticationProvider接⼝,authenticate⽅法参数Authentication与attemptAuthentication⽅法返回的是同⼀个对象,重
写 authenticate(Authentication authentication),其中supports(Class<?> authentication)⽅法⽤来指定当前检验规则是针对哪个AbstractAuthenticationToken⼦类对象。springboot⾃带默认的登录验证是返回UsernamePasswordAuthenticationToken对象。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论