package com.example.blogsystem.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
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.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
@EnableWebSecurity // 开启MVC security安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Value("${COOKIE.VALIDITY}")
private Integer COOKIE_VALIDITY;
/**
* 重写configure(HttpSecurity http)方法,进行用户授权管理
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 1、自定义用户访问控制
http.authorizeRequests()
.antMatchers("/","/page/**","/article/**","/login").permitAll()
.antMatchers("/back/**","/assets/**","/user/**","/article_img/**").permitAll()
.antMatchers("/admin/**").hasRole("admin")
.anyRequest().authenticated();
// 2、自定义用户登录控制
http.formLogin()
.loginPage("/login")
.usernameParameter("username").passwordParameter("password")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
String url = httpServletRequest.getParameter("url");
// 获取被拦截的原始访问路径
RequestCache requestCache = new HttpSessionRequestCache();
SavedRequest savedRequest = requestCache.getRequest(httpServletRequest,httpServletResponse);
if(savedRequest !=null){
// 如果存在原始拦截路径,登录成功后重定向到原始访问路径
httpServletResponse.sendRedirect(savedRequest.getRedirectUrl());
} else if(url != null && !url.equals("")){
// 跳转到之前所在页面
URL fullURL = new URL(url);
httpServletResponse.sendRedirect(fullURL.getPath());
}else {
// 直接登录的用户,根据用户角色分别重定向到后台首页和前台首页
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean isAdmin = authorities.contains(new SimpleGrantedAuthority("ROLE_admin"));
if(isAdmin){
httpServletResponse.sendRedirect("/admin");
}else {
httpServletResponse.sendRedirect("/");
}
}
}
})
// 用户登录失败处理
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
// 登录失败后,取出原始页面url并追加在重定向路径上
String url = httpServletRequest.getParameter("url");
httpServletResponse.sendRedirect("/login?error&url="+url);
}
});
// 3、设置用户登录后cookie有效期,默认值
http.rememberMe().alwaysRemember(true).tokenValiditySeconds(COOKIE_VALIDITY);
// 4、自定义用户退出控制
http.logout().logoutUrl("/logout").logoutSuccessUrl("/");
// 5、针对访问无权限页面出现的403页面进行定制处理
http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
// 如果是权限访问异常,则进行拦截到指定错误页面
RequestDispatcher dispatcher = httpServletRequest.getRequestDispatcher("/errorPage/comm/error_403");
dispatcher.forward(httpServletRequest, httpServletResponse);
}
});
}
/**
* 重写configure(AuthenticationManagerBuilder auth)方法,进行自定义用户认证
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 密码需要设置编码器
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// 使用JDBC进行身份认证
String userSQL ="select username,password,valid from t_user where username = ?";
String authoritySQL ="select u.username,a.authority from t_user u,t_authority a," +
"t_user_authority ua where ua.user_id=u.id " +
"and ua.authority_id=a.id and u.username =?";
auth.jdbcAuthentication().passwordEncoder(encoder)
.dataSource(dataSource)
.usersByUsernameQuery(userSQL)
.authoritiesByUsernameQuery(authoritySQL);
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
基于SpringBoot+mysql的个人博客系统.zip
共236个文件
png:51个
jpg:40个
js:35个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 165 浏览量
2023-10-29
19:45:26
上传
评论
收藏 15.06MB ZIP 举报
温馨提示
1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 -------- 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。
资源推荐
资源详情
资源评论
收起资源包目录
基于SpringBoot+mysql的个人博客系统.zip (236个子文件)
mvnw.cmd 7KB
amazeui.flat.css 336KB
amazeui.css 336KB
amazeui.flat.min.css 312KB
amazeui.min.css 311KB
bootstrap.min.css 118KB
style.min.css 71KB
mditor.css 58KB
mditor.min.css 48KB
style.min.css 34KB
font-awesome.min.css 30KB
select2.css 17KB
select2.css 17KB
layer.css 14KB
select2.min.css 14KB
sweetalert2.min.css 14KB
dropzone.min.css 9KB
app.css 7KB
jquery.steps.css 5KB
toggles.css 5KB
style.css 5KB
admin.css 5KB
select2-bootstrap.css 3KB
select2-bootstrap.css 3KB
select2-bootstrap.min.css 3KB
multi-select.min.css 2KB
jquery.tagsinput.css 1KB
xcode.min.css 822B
xcode.min.css 822B
basic.min.css 751B
674f50d287a8c48dc19ba404d20fe713.eot 162KB
fontawesome-webfont.eot 59KB
loading.gif 64KB
loading-0.gif 6KB
select2-spinner.gif 2KB
select2-spinner.gif 2KB
select2-spinner.gif 2KB
loading-2.gif 2KB
loading-1.gif 701B
.gitignore 395B
article_edit.html 7KB
comments.html 6KB
header.html 5KB
index.html 4KB
article_list.html 4KB
index.html 3KB
header.html 3KB
paging.html 3KB
login.html 3KB
articleDetails.html 1KB
footer.html 1KB
error_404.html 1KB
error_403.html 1KB
tale_comment.html 1KB
footer.html 639B
maven-wrapper.jar 59KB
SecurityConfig.java 7KB
AdminController.java 4KB
ArticleServiceImpl.java 4KB
RedisConfig.java 4KB
Commons.java 3KB
IndexController.java 3KB
ArticleResponseData.java 3KB
Article.java 3KB
SiteServiceImpl.java 2KB
MyUtils.java 2KB
CommentController.java 2KB
Comment.java 2KB
StatisticMapper.java 2KB
LoginController.java 2KB
CommentServiceImpl.java 2KB
BaseInterceptor.java 1KB
ScheduleTask.java 1KB
ArticleMapper.java 1KB
CommentMapper.java 1KB
MailUtils.java 909B
Statistic.java 886B
IArticleService.java 721B
StaticticsBo.java 677B
WebMvcConfig.java 661B
BlogSystemApplication.java 621B
ISiteService.java 600B
ICommentService.java 353B
BlogSystemApplicationTests.java 350B
3.jpg 963KB
4.jpg 604KB
4.jpg 455KB
4.jpg 428KB
3.jpg 399KB
1.jpg 369KB
5.jpg 355KB
3.jpg 348KB
2.jpg 320KB
1.jpg 318KB
2.jpg 300KB
3.jpg 289KB
5.jpg 277KB
1.jpg 256KB
6.jpg 249KB
5.jpg 242KB
共 236 条
- 1
- 2
- 3
资源评论
程皮
- 粉丝: 257
- 资源: 2485
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功