使用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请求,在完成注销之后,页面展现相应的成功消息。

猜你喜欢

转载自blog.csdn.net/chimmhuang/article/details/80460222