首页 课程 师资 教程 报名

Spring security视频教程,实战精讲

  • 2021-02-02 16:39:06
  • 868次 星辉

Spring Security是一个基于Spring的安全框架,提供了一套Web应用安全性的完整解决方案。一般来说,Web应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。

 

spring security视频教程

 

用户认证一般要求用户提供用户名和密码,系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

 

1.项目创建

 

Spring Boot中使用Spring Security非常容易,引入依赖即可:

 

Spring security视频教程

 

pom.xml 中的 Spring Security 依赖:

 

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

 

只要加入依赖,项目的所有接口都会被自动保护起来。

 

2.初次体验

 

我们创建一个HelloController:

 

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

 

访问 /hello ,需要登录之后才能访问。

 

Spring security视频教程

 

当用户从浏览器发送请求访问 /hello 接口时,服务端会返回 302 响应码,让客户端重定向到 /login 页面,用户在 /login 页面登录,登陆成功之后,就会自动跳转到 /hello 接口。

 

另外,也可以使用 POSTMAN 来发送请求,使用 POSTMAN 发送请求时,可以将用户信息放在请求头中(这样可以避免重定向到登录页面):

 

Spring security视频教程

 

通过以上两种不同的登录方式,可以看出,Spring Security支持两种不同的认证方式:

 

可以通过form表单来认证

 

可以通过HttpBasic来认证

 

3.用户名配置

 

默认情况下,登录的用户名是user,密码则是项目启动时随机生成的字符串,可以从启动的控制台日志中看到默认密码:

 

Spring security视频教程

 

这个随机生成的密码,每次启动时都会变。对登录的用户名/密码进行配置,有三种不同的方式:

 

在application.properties中进行配置

 

通过Java代码配置在内存中

 

通过Java从数据库中加载

 

前两种比较简单,第三种代码量略大,本文就先来看看前两种,第三种后面再单独写文章介绍,也可以参考我的微人事项目。

 

3.1配置文件配置用户名/密码

 

可以直接在application.properties文件中配置用户的基本信息:

 

spring.security.user.name=javaboy
spring.security.user.password=123

 

配置完成后,重启项目,就可以使用这里配置的用户名/密码登录了。

 

3.2 Java配置用户名/密码

 

也可以在Java代码中配置用户名密码,首先需要我们创建一个Spring Security的配置类,集成自WebSecurityConfigurerAdapter类,如下:

 

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //下面这两行配置表示在内存中配置了两个用户
        auth.inMemoryAuthentication()
                .withUser("javaboy").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")
                .and()
                .withUser("lisi").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");
    }
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 

这里我们在configure方法中配置了两个用户,用户的密码都是加密之后的字符串(明文是123),从Spring5开始,强制要求密码要加密,如果非不想加密,可以使用一个过期的PasswordEncoder的实例NoOpPasswordEncoder,但是不建议这么做,毕竟不安全。

 

Spring Security中提供了BCryptPasswordEncoder密码编码工具,可以非常方便的实现密码的加密加盐,相同明文加密出来的结果总是不同,这样就不需要用户去额外保存盐的字段了,这一点比Shiro要方便很多。

 

4.登录配置

 

对于登录接口,登录成功后的响应,登录失败后的响应,我们都可以在WebSecurityConfigurerAdapter的实现类中进行配置。例如下面这样:

 

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    VerifyCodeFilter verifyCodeFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http
        .authorizeRequests()//开启登录配置
        .antMatchers("/hello").hasRole("admin")//表示访问 /hello 这个接口,需要具备 admin 这个角色
        .anyRequest().authenticated()//表示剩余的其他接口,登录之后就能访问
        .and()
        .formLogin()
        //定义登录页面,未登录时,访问一个需要登录之后才能访问的接口,会自动跳转到该页面
        .loginPage("/login_p")
        //登录处理接口
        .loginProcessingUrl("/doLogin")
        //定义登录时,用户名的 key,默认为 username
        .usernameParameter("uname")
        //定义登录时,用户密码的 key,默认为 password
        .passwordParameter("passwd")
        //登录成功的处理器
        .successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("success");
                    out.flush();
                }
            })
            .failureHandler(new AuthenticationFailureHandler() {
                @Override
                public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("fail");
                    out.flush();
                }
            })
            .permitAll()//和表单登录相关的接口统统都直接通过
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("logout success");
                    out.flush();
                }
            })
            .permitAll()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }
}

 

我们可以在successHandler方法中,配置登录成功的回调,如果是前后端分离开发的话,登录成功后返回JSON即可,同理,failureHandler方法中配置登录失败的回调,logoutSuccessHandler中则配置注销成功的回调。

 

5.忽略拦截

 

如果某一个请求地址不需要拦截的话,有两种方式实现:

 

设置该地址匿名访问

 

直接过滤掉该地址,即该地址不走Spring Security过滤器链

 

推荐使用第二种方案,配置如下:

 

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vercode");
    }
}

 

零基础学习Spring Security,推荐星辉的Spring Security视频教程,本课程细说Spring Security这套安全框架,通过案例带你快速学习掌握Spring Security。

 

前提条件:学习过Spring及SpringBoot的人群。

 

环境参数:Idea,JDK8,maven 3+,spring boot 2.0.6,spring security 5.0.9

 

推荐语:Spring Security安全框架,基于Spring家族,认证授权领域的“扛把子”,Java开发必备。

 

spring security视频教程

 

以上就是星辉Java培训机构的小编针对“Spring security视频教程,实战精讲”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交