SpringSecurity


SpringSecurity

springsecurity是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
springsecurity是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring安全性的真正威力在于它可以很容易地扩展以满足定制需求。


简单使用

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

创建boot项目,导入security依赖,编写一个主页controller,启动项目后访问,发现跳到一个登录页面。
登录
于是猜想是security提供的登录页面,查看properties,找到了用户名为user,密码为随机生成的uuid,并且打印在了控制台,于是登录成功。
密码
既然是配置类,当然就可以配置密码等。

spring.security.user.password=123456

简单的授权及认证

@EnableWebSecurity
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");

        //没有权限默认跳到security的login登录页,loginpage设置请求自己的login页面
        http.formLogin().loginPage("/toLogin");

        //开启注销,security的logout
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
        //开启记住我,cookies实现
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存用户认证
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("yao")
            .password(new BCryptPasswordEncoder().encode("123456"))
            .roles("vip2","vip3")
            .and()
            .withUser("root")
            .password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");

    }
}

SpringSecurity官方文档

<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

thymeleaf和security有很好的支持,通过一些标签语法可以实现前端的认证。

判断权限
<div class="column" sec:authorize="hasRole('vip2')">
是否登录
<div sec:authorize="isAuthenticated()">
读取用户名和权限
<a class="item">
   用户名: <span sec:authentication="name"></span>
   角色: <span sec:authentication="principal.authorities"></span>
</a>
等等

总结

security的核心思想是aop,在没有改变源代码的情况下,通过javaconfig形式的配置文件,就能对于认证和授权进行配置。更多配置形式可以参照源码上的注释以及官方文档。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值