spring security的学习笔记(一)

spring security的学习(一)

Spring Security是功能强大的并高度可定制的认证和访问控制框架。

一、简介

一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如我们所熟知的普通用户和管理员,能访问的资源不同。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

认证:识别并构建用户对象,如:根据请求中的username,获取登录用户的详细信息,判断用户状态,缓存用户对象到请求上下文等。
决策:判断用户能否访问当前请求,如:识别请求url,根据用户、权限和资源(url)的对应关系,判断用户能否访问当前请求url。

二、SpringSecurity框架(一)xml方式

1.在pom.xml文件引入以下依赖

<!--spring Security/身份验证-->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>

2.配置web.xml文件
spring Security 安全认证 监听器,读取配置文件,创建security容器

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring-security.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--   spring Security 安全认证 监听器,过滤器链在web中注册 
   这些过滤器实际是在spring容器中管理,这里只是代理注册给web容器   -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3.添加配置文件 spring-security.xml

<!--1、设置放行资源,如登录注册页面,静态资源css、js等等
        security="none" 设置此资源不被拦截。 -->
<http pattern="/login.html" security="none"></http>
<http pattern="/loginerror.html" security="none"></http>
<http pattern="/css/**" security="none"></http>
<http pattern="/img/**" security="none"></http>
<http pattern="/js/**" security="none"></http>
<http pattern="/plugins/**" security="none"></http>

<http>
    <!-- 2、拦截所有(除放行资源外) -->
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
    <!-- 
        3、登录表单设置
        1)login-page:指定登录页面;
        2)login-processing-url:指定登录请求路径;
        3)default-target-url:指定了成功进行身份验证和授权后默认呈现给用户的页面;
        4)always-use-default-target:指定了是否在身份验证通过后总是跳转到; 
                                   default-target-url 属性指定的 URL。
        5)authentication-failure-url:指定了身份验证失败时跳转到的页面; -->
    <form-login login-page="/login.html" 
                login-processing-url="/login"
                always-use-default-target="true" 
                default-target-url="/admin/index.html"
                authentication-failure-url="/loginerror.html"      />
    <!--   4、注销设置
              1)logout-url:指定注销的url;
              2)logout-success-url:注销成功后登录返回的页面。 -->         
    <logout logout-url="/logout" logout-success-url="/login.html"/>          
    <!-- 
        5、跨站请求设置(我们这里关闭)
           1)csrf disabled="true" 关闭 csrf ,如果不加会出现错误

           2)CSRF(Cross-site request forgery):跨站请求伪造,
             也被称为“One Click Attack”或者 SessionRiding,
             通常缩写为 CSRF 或者 XSRF,是一种对网站的恶意利用。 -->            
    <csrf disabled="true" />

    <!-- 6、iframe 框架结构展示 -->
    <headers>
        <frame-options policy="SAMEORIGIN" />
    </headers>
</http>

4.新建一个类命名为SecurityConfig,主要用于开启spring security和创建测试角色。

@EnableWebSecurity  // 此注解用于开启Spring Security的功能
public class SecurityConfig {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
                 // 内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER
                  auth
                      .inMemoryAuthentication()
                          .withUser("user").password("password").roles("USER");
              }
}

5.启动项目,输入所创建的用户名和密码,如图。

三、SpringSecurity框架(二)基于java配置

1.在pom.xml文件引入以下依赖

<!--spring Security/身份验证-->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>

2.开启Spring Security:在配置类头上加注解@EnableWebSecurity
3.自定义登录界面

 @EnableWebSecurity  // 此注解用于开启Spring Security的功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
                 http //支持基于http验证
                     .authorizeRequests()
                         .antMatchers("/", "/index").permitAll()  // 允许"/", "/index"的请求访问
//                         .antMatchers("/resources/**").permitAll() //验证每个请求,除了以“/resources/”开头的URL
                         .anyRequest().authenticated()
                         .and()
                     .formLogin() //支持基于表单验证,登录页面为“/login”对应的文件
                         .loginPage("/login")//请求验证时被重定向到 /login
                                             // 验证失败失败时被重定向到 /login?error
                                             // 登出成功时会被重定向到 /login?logout
                         .permitAll() //允许在未验证时任何访问到的资源和URL,如果不加则连访问/login 都会一直被重定向
                         .and()
                     .logout()
                         .permitAll();
             }
             }

4.为了便于页面之间的相互跳转,我在这里使用了thymeleaf模板引擎

<!--thymeleaf模板引擎-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

5.再编写一个controller类,用于页面跳转

@Controller
public class HelloController {

@GetMapping("/")
public String index() {
    return "index";
}

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

@RequestMapping("/login")
public String login() {
    return "login";
    }
}

6.启动项目,登陆,输入对用的用户名和密码,进入主页
登陆:
在这里插入图片描述
主页:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值