使用Spring Security进行安全控制

Spring Security进行安全控制

文章内容来自于:http://blog.didispace.com/springbootsecurity/,作者:程序员DD
文章主要用于自己学习SpringBoot,方便以后的查询

Spring Security有点类似拦截器

1.添加依赖

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

2.在与Application.java同级目录下创建WebSecurity.java

@Configuration //通过@Configuration注解,让Spring来加载该类配置
@EnableWebSecurity //通过@EnableWebSecurity直接来启用WebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //授权请求 --> 定义哪些URL需要被保护、哪些不需要被保护。
                    //例如指定了/和/home不需要任何认证就可以访问,其他路径必须通过身份认证
                    .antMatchers("/","/home").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin() //通过formLogin()定义当需要用户登陆的时候,转到的登陆页面
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();

        /*
            http.授权管理()
                    .蚂蚁匹配者().许可所有()
                    .任何请求().认证()
                    .以及()
                .表单登陆()
                    .登陆页面()
                    .许可所有()
                    .以及()
                .登出()
                    .许可所有()
         */

    }


    /**
     * 在内存中创建了一个用户,该用户的名称为user,密码为passwrod,用户角色为USER
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
  • 通过@EnableWebSecurity注解开启Spring Security的功能
  • 继承WebSecurityConfigurerAdapter 。并重写它的方法来设置一些web安全的细节
  • configure(HttpSecurity http)方法
    • 通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。例如以上代码指定了//home不需要任何认证就可以访问,其他的路径都必须通过身份验证。
    • 通过formLogin()定义当需要用户登陆的时候,转到的登陆页面。
  • configureGlobal(AuthenticationManagerBuilder auth)方法,在内存中创建了一个用户,该用户的名称user,密码password,用户角色为USER

根据配置,Spring Security提供了一个过滤器来拦截请求并验证用户身份。如果用户身份认证失败,页面就重定向到/login?error,并且页面中会展现相应的错误信息。若用户想要注销登录,可以通过访问/login?logout请求,在完成注销之后,页面展现相应的成功消息。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值