zoukankan      html  css  js  c++  java
  • Spring Security之简单举例

    核心功能

    Spring Security提供了三个核心的功能:

    认证(你是谁)

    授权(你能干什么)

    攻击防护(防止伪造身份)

    一个简单例子

    默认情况

    在前面的开发中,都是将spring security功能禁用的,现在开启该功能,即在application.properties文件中把下面这句话注释掉即可。

    # security.basic.enabled=false
    # 注:在添加了BrowserSecurityConfig之后,security.basic.enabled这个配置就不管用了
    

    重启应用会在控制台输出一个默认密码,对应的用户名是user

    再访问http://localhost:8080/user/1时会提示输入用户名密码,默认情况下是httpBasic认证.

    自定义认证模式

    认证授权相关的代码写在各个模块里,处理浏览器相关的代码写在imooc-security-browser模块里。写在imooc-security-browser模块里的配置能在demo模块里起作用,原因是demo中的起动类在com.imooc包下,而BrowserSecurityConfig在com.imooc.security.browser.config包下,注意启动类和配置类所在的包,要不然配置类会不起作用的

    httpBasic登录,在imooc-security-browser模块里添加如下配置类,实现了自定义的httpBasic登录,即默认的认证模式:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            System.out.println("BrowserSecurityConfig");
            http.httpBasic() // httpBasic登录
                    .and()
                    .authorizeRequests() // 对请求做授权
                    .anyRequest() // 任何请求
                    .authenticated(); // 都需要身份认证
        }
    }
    

    httpForm登录,下面的代码是基于表单的登录:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            System.out.println("BrowserSecurityConfig");
            // 写法一:继承父类是formLogin登录
            // super.configure(http);
            
            // 写法二
            http.formLogin() // 表单登录
                    .and()
                    .authorizeRequests() // 对请求做授权
                    .anyRequest() // 任何请求
                    .authenticated(); // 都需要身份认证
        }
    }
    

    基本原理

    最核心的东西就是过滤器链,绿色过滤器可控制,用来处理表单登录,其他颜色过滤器不可控制,其中蓝色用来处理异常,橙色用来作最终能否访问的认证,REST API就是我们写的控制器。

    请求到UsernamePasswordAuthenticationFilter,会判断是否是登录请求,是的话是否有用户名和密码并认证,到FilterSecurityInterceptor时会根据配置判断请求是否满足要求(是否已认证或不用认证),如果不满足就返回登录让用户登录认证信息。通过在上面几个控制器打断点,来分析一下:

    启动应用并访问http://localhost:8080/user/1,首先会FilterSecurityInterceptor.java,对请求做验证,判断没有认证信息后抛出异常

    异常信息被ExceptionTranslationFilter.java过滤器捕获并重定向到登录页面

    从控制台复制密码,并在页面输入登录信息,点击登录按钮

    登录请求被UsernamePasswordAuthenticationFilter.java过滤器拦截,并对用户信息进行认证

    再次被FilterSecurityInterceptor.java拦截器拦截,按F8

    最终访问/user/1对应的控制器

  • 相关阅读:
    fstat、stat和lstat 区别
    listen()函数中的SOMAXCONN含义
    #ifndef#define#endif的用法(整理)
    stdin和STDIN_FILENO的区别(转)
    S_ISREG等几个常见的宏
    *_t 数据类型
    IO模式精细讲解: MSG_DONTWAIT 、 MSG_WAITALL
    c标准函数库(查阅使用)
    stdint.h
    C# RichTextBox控件常用屬性和事件
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9752170.html
Copyright © 2011-2022 走看看