SpringSecurity配置

一、导入依赖

<!-- SpringSecurity 对 Web 应用进行权限管理 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 配置 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 标签库 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>4.2.10.RELEASE</version>
</dependency>

二、环境搭建

在web.xml中加入springSecurityFilterChain过滤器(名称不可变),如果配置无效,需考虑将Spring IOC容器和SpringMVC IOC容器合二为一。

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

三、编写项目

1.配置SpringSecurity

1)基于xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">

    <security:http>
        <security:http-basic/>
        <security:form-login/>
        <security:intercept-url pattern="/**" access="isAuthenticated()"/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="tom" password="123456" authorities="ROLE_USER"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

2)基于配置类

测试方法:基于内存

// 开启配置类注解
@Configuration
// 开启基于web的security
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存
        auth
                .inMemoryAuthentication()
                .withUser("tom")
                .password("123456")
                .roles("ADMIN", "练气")
                .and()
                .withUser("jeck")
                .password("123456")
                .authorities("UPDATE")
                .roles("练气", "元婴")
        ;
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        //引入jdbc
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);

        security
                .authorizeRequests()   //对请求进行授权
                .antMatchers("/index.jsp", "/layui/**")   //对index.jsp授权
                .permitAll()   //无条件访问
                .antMatchers("/level1/**")
                .hasRole("Admin")
                .antMatchers("/level2/**")
                .hasRole("User")
                .and()
                .authorizeRequests()   //对请求进行授权
                .anyRequest()   //任意请求
                .authenticated()   //需要登录后才能访问
                .and()
                .formLogin()   //使用表单形式登录
                .loginPage("/index.jsp")   //指定登录页
                .permitAll()   //设置登录页所有人可以访问
                .loginProcessingUrl("/do/login.html")   //自定义登录请求路径
                .usernameParameter("loginAcct")   //自定义登录账号参数名
                .passwordParameter("userPswd")   //自定义登录密码参数名
                .defaultSuccessUrl("/main.html")   //自定义登陆成功默认路径
                .and()
                .csrf()
                .disable()   // 禁用csrf功能
                .logout()
                .logoutUrl("/do/logout.html")
                .logoutSuccessUrl("/index.jsp")
                .and()
                .exceptionHandling()
                .accessDeniedPage("/WEB-INF/views/no_auth.jsp")
                .and()
                .rememberMe()   //开启记住我功能
                .tokenRepository(jdbcTokenRepository)   //保存到数据库
        ;
    }
}

 真正配置:基于数据库

//盐值加密
@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)   //自定义用户权限
            .passwordEncoder(passwordEncoder)
    ;
}
@Component
public class AppUserDetailsService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询Admin对象
        String sql="SELECT id,loginacct,userpswd,username,email,createtime FROM t_admin WHERE loginacct = ?";
        List<Admin> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), username);
        Admin admin = list.get(0);
        //给Admin设置角色权限信息
        List<GrantedAuthority> authorities= AuthorityUtils.createAuthorityList("ROLE_ADMIN","UPDATE");

        return new User(username,admin.getUserpswd(),authorities);
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值