SpringSecurity

    Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。

    一般来说, Web 应用的安全性包括用户认证( Authentication )和用 户授权( Authorization)两个部分。
    ①用户认证指的是验证某个用户是否为系统中的合法主体,也就是说 用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
    在用户认证方面, Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、 HTTP 表单验证、 HTTP 摘要认证、 OpenID 和 LDAP 等。
    ②用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权 限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系 统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
    在用户授权方面, Spring Security 提供了基于角色的访问控制和访问控制列表( Access Control List, ACL ),可以对应用中的领域对象进行细粒度的控制。

官方文档: Spring Security Reference
1.引入模块
<dependency> 
<groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
2.框架
@EnableWebSecurity  // 开启WebSecurity模式
public class securityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        super.configure(http);
    }


}

3.进入父类中可以查看方法

4.从内存中授权,登录(也可从数据库授权,暂略)

授权:

//授权

@EnableWebSecurity // 开启WebSecurity模式
public class securityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        // 首页所有人可以访问
        // 定制请求的授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        // /login 请求来到登录页
        //没有权限会默认到登陆页面   /Login
        http.formLogin();

    }

认证:

//认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //可以从数据库或内存里认证

        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
        // 要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        // spring security 官方推荐的是使用bcrypt加密方式
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("taozi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3");


    }

5.权限控制和注销

 P36

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值