spring Security项目快速搭建

spring Security的底层原理就是拦截器链。在上一篇文章使用注解方式搭建spring项目中,

可以自定义一套拦截器,拦截实现spring提供的HandlerInterceptr接口,然后实现三个拦截器方法,

在prexxx方法中定义验证逻辑。拦截器定义好后在servletContext容器的配置类中注入进来再进行注册。就可以使用。

这是基于session进行认证授权的方式。

spring Security为我们提供了认证授权的框架。下面大概上说明一下怎么快速搭建一个spring Security项目。

1 创建maven工程

2 pom依赖,加上spring Security的相关依赖

    <dependency>

      <groupId>org.springframework.security</groupId>

      <artifactId>spring-security-web</artifactId>

扫描二维码关注公众号,回复: 9014491 查看本文章

      <version>5.1.5.RELEASE</version>

    </dependency>

    <dependency>

      <groupId>org.springframework.security</groupId>

      <artifactId>spring-security-config</artifactId>

      <version>5.1.5.RELEASE</version>

    </dependency>

3 和上篇文章一样,创建两个配置文件 ,一个是spring容器相当于applicationContext.xml,

   一个是servletContext容器,向当与springmvc.xml.这里面不用注册自己的拦截器。

4 加载spring容器

5 安全配置 在配置包下定义

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigAdapetor{

  //配置用户信息服务

  @Bean

  public UserDetailsService userDetailsService(){

    InMemoryUserDetailManger manger = new InMemoryUserDetailManger();

    manger,createUser(User.withUsername("zhangsan").password("111").authorities("a1","a2").build()));

    manger,createUser(User.withUsername("lisi").password("222").authorities("b1","b2").build()));

    return manger ;

  } 

  //定义密码编码器

  @Bean

  public PasswordEncoder passwordEncoder(){

    return noOpPasswordEncoder .getIntance() ;

  } 

  //定义安全拦截机制

  @Bean

  protected void configure(HttpSecurity http) throws Exception{

    http.authorizeRequests()

    .antMatchers("/r/**").authenticated()

    .anyRequest().permitAll()

    .and()

    .formLogin()

    .sucessFowardUrl("/login-sucess");

  } 

}

6 在加载类中加载此配置

  在getRootConfigClasses方法中,在数组中加上此配置的class。

7 初始化spring Security.由于当前使用spring环境,所以不需要多余代码

  如果没有使用spring环境,就需要将WebSecurityConfig(spring Security配置类)传入父类,

  以便获取配合,创建spring context

public class SpringSecurotyApplicationInitializer extends AbstractSecurityWebApplicationInitializer{

  public SpringSecurotyApplicationInitializer (){

    //super(WebSecurityConfig);   //如果没有spring或springMvc就需要加上此行

  }

}

8 当点击登录时候(认证结束)需要跳转到我们自己的页面去,所以需要修改配置servletContext里面的登录地址 即:

  

        Override

        public void addViewControlers(viewControllerRegistry registry){

          registry.addViewController("/").setViewName("redirect:/login");

        }

9  在controller中定义 /login-sucess 的请求。spring Security默认退出的请求是 /logout

10 测试 

11 配置授权 在配置类中配置

    http.authorizeRequests()

    .antMatchers("/r/r1").hasAuthority("a1")

    .antMatchers("/r/r2").hasAuthority("b1")

    .antMatchers("/r/**").authenticated()

    .anyRequest().permitAll()

    .and()

    .formLogin()

    .sucessFowardUrl("/login-sucess");

猜你喜欢

转载自www.cnblogs.com/dengw125792/p/12283901.html