首页 > 其他分享 >Spring Security 一个小 Demo

Spring Security 一个小 Demo

时间:2023-05-02 14:12:15浏览次数:39  
标签:Spring boot springframework annotation Demo org import Security security

参考教程

主要参考了 Spring Security最简单全面教程(带Demo)

问题解决

遇到了 javax.servlet.ServletException: Circular view path 的问题,访问 http://localhost:8080/login 时一直 404。

Thymeleaf 依赖

看到 HTML 文件里面有用到 th:if= 的语法,参考 SpringBoot整合Thymeleaf快速入门(附详细教程) 添加了依赖

视图解析

还是访问不了,发现模板是默认放到 templates 文件夹下的,但是移动后还是访问不了。参考 springboot视图解析器配置(yml版配置) 配置了视图解析,就可以了。

最终结果

实践效果

访问 http://localhost:8080/home 时不用验证。

访问 http://localhost:8080/hello 会自动跳转到 login 页。

只有 admin 用户可以访问 http://localhost:8080/admin 页。

代码地址

项目地址

核心代码

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fun.seolas</groupId>
    <artifactId>spring-security-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>
application.yaml
#yml配置
spring:
  mvc:
    #  视图解析器
    view:
      prefix: /imf/
      suffix: .html
    #  静态资源访问前缀(区分动态资源和静态资源)
    static-path-pattern: /imf/**
  #  静态资源的加载路径
  resources:
    static-locations: classpath:/templates/
SecurityConfig.java
package fun.seolas.config;

import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity  //启用Web安全功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //访问"/"和"/home"路径的请求都允许
                .antMatchers("/", "/home", "/staff", "/staff/*")
                .permitAll()
                //而其他的请求都需要认证
                .anyRequest()
                .authenticated()
                .and()
                //修改Spring Security默认的登陆界面
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存来存储用户信息
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER").and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("456")).roles("USER", "ADMIN");
    }
}
MethodSecurityConfig.java
package fun.seolas.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
SecurityController.java
package fun.seolas.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SecurityController {

    @GetMapping(value = {"/home","/"})
    public String home(){
        return "home";
    }

    @GetMapping(value = "/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping(value = "/login")
    public String login(){
        return "login";
    }

    @GetMapping(value = "/admin")
    @Secured("ROLE_ADMIN")
    public String admin(){
        return "admin";
    }
}

标签:Spring,boot,springframework,annotation,Demo,org,import,Security,security
From: https://www.cnblogs.com/seolas/p/17367626.html

相关文章

  • springboot常用注解
    ......
  • Spring Boot 整合邮件服务
    参考教程首先参考了SpringBoot整合邮件配置,这篇文章写的很好,按照上面的操作一步步走下去就行了。遇到的问题版本配置然后因为反复配置版本很麻烦,所以参考了如何统一引入SpringBoot版本?。FreeMarker在配置FreeMarker时,发现找不到FreeMarkerConfigurer类,参考了spri......
  • springboot 静态资源导入
    1.根据源码可以看到需要去webjars官网下载jquery的依赖<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>2.2.4</version></dependency>2.读源码 总结: 1.在springboot中可以使用以下五种方式处理静态资源:we......
  • Spring源码:Bean的生命周期(二)
    前言让我们继续讲解Spring的Bean实例化过程。在上一节中,我们已经讲解了Spring是如何将Bean定义加入到IoC容器中,并使用合并的Bean定义来包装原始的Bean定义。接下来,我们将继续讲解Spring的getBean()方法,特别是针对FactoryBean的解析。在getBean()方法中,Spring还支持......
  • springSecurity过滤器之AnonymousAuthenticationFilter
    SpringSecurity提供了匿名登录功能,让我们不登录也能访问。比如/anoy路径及子路径都能匿名访问,配置如下:@ConfigurationpublicclassMySecurityConfigextendsWebSecurityConfigurerAdapter{@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException......
  • SpringBoot高频面试题
    Springboot的优点内置servlet容器,不需要在服务器部署tomcat。只需要将项目打成jar包,使用java-jarxxx.jar一键式启动项目SpringBoot提供了starter,把常用库聚合在一起,简化复杂的环境配置,快速搭建spring应用环境可以快速创建独立运行的spring项目,集成主流框架准生产环境的......
  • Spring事务
    事务作用:在数据层保障一系列的数据库操作同成功同失败Spring事务作用:在数据层或业务层保障一系列的数据库操作,同成功同失败案例:银行账户转账1.在业务层接口上添加Spring事务管理2.设置事务管理器3.开启注解式事务驱动事务角色事务管理员:发起事务方,在Spring中通常指代业务......
  • Java教程:Springboot项目如何使用Test单元测试
    今天早上来公司领导突然分配了任务,就是简单的测试一下实体的添加修改功能,要使用到Juntil单元测试,目前使用springboot项目,jpa,maven管理,回忆起曾经用到过@Test注解,于是开始唰唰唰的写起了测试咧,然鹅,一顿报错,依赖无法注入,空指针,乱七八糟的一大通,无奈开始借助百度,终于实现了单元测试,......
  • SpringBoot项目使用 validation进行数据校验
    validation进行数据校验@Validated注解和@Valid注解都是SpringFramework中用于数据校验的注解,但它们有以下几点区别:所在包路径不同:@Valid注解位于javax.validation.constraints包下,而@Validated注解位于org.springframework.validation.annotation包下。支持......
  • Springboot @Test 给Controller接口 写 单元测试
    Springboot@Test给Controller接口写单元测试https://blog.csdn.net/qq_35387940/article/details/129140984?spm=1001.2101.3001.6650.8&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-8-129140984-blog-103569814.235%5Ev32......