当前位置: 首页 > article >正文

springsecurity使用

一项目添加springsecurity,保护方法不被调用,登录后可调用实现

1 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2 springsecurity配置

//开启方法级保护,如:@PreAuthorize("has Authority('ROLE_ADMIN')")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("admin").password(new BCryptPasswordEncoder().encode("123")).roles("USER").build());
        return manager;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/css/**","/index").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/a").anonymous()
                .and()
                .formLogin().loginPage("/login").failureUrl("/login-error")
                .and()
                .exceptionHandling().accessDeniedPage("/401");
        http.logout().logoutSuccessUrl("/");
    }
}

3 登录跳转被保护页面流程
首先进入免登录的首页,当点击链接进入受到保护页面时,此时因没有登录,页面自动跳到登录页面,在登录页面输入有USER角色的账号时,自动跳到请求的href="/user/index"后台

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
  <p>这个页面没有受到保护</p>
  <p th:text="${tip}"></p>
  <form action="#" th:action="@{/logout}" method="post">
    <input type="submit" value="登出">
  </form>
<ul>
    <li>点击<a href="/user/index" th:href="@{/user/index}">跳转到user/index已被保护的界面</a></li>
</ul>
</body>
</html>

http://www.kler.cn/news/357866.html

相关文章:

  • STL-vector+题目
  • Python爬虫:获取数据的入门详解
  • qt creator 开发环境的安装
  • 【论文笔记】X-Former: Unifying Contrastive and Reconstruction Learning for MLLMs
  • 如何通过CDN优化网站服务器访问速度?
  • AWD学习
  • 【英特尔IA-32架构软件开发者开发手册第3卷:系统编程指南】2001年版翻译,1-11
  • R语言医学数据分析实践-R编程环境的搭建
  • 【在Linux世界中追寻伟大的One Piece】应用层自定义协议|序列化
  • linux笔记(yum本地源仓库搭建)
  • arp欺骗及其实验
  • 简单介绍$listeners
  • Linux服务器安装SRAToolkit教程
  • 3D Gaussian Splatting前向渲染代码解读
  • 鸿蒙网络编程系列28-服务端证书锁定防范中间人攻击示例
  • JavaWeb环境下的Spring Boot在线考试系统开发
  • LiveKit 在Kylin Server V10 下离线安装和配置
  • DataWhale10月动手实践——Bot应用开发task02学习笔记
  • 基于基于jsp+mysql+Spring+mybatis的SSM汽车保险理赔管理系统设计和实现
  • bash之基本运算符