SpringSecurity(Web权限方案)

30 篇文章 0 订阅
20 篇文章 0 订阅

SpringSecurity

一、基本概要

1、认证和授权

1、认证:用户是否登录

2、授权:用户是否有权利去做别的东西

2、特点

  • 全面的权限控制
  • 为web开发设计
  • 旧版本不能脱离Web环境
  • 新版本对整个框架进行分层抽取,分层核心模块和web模块。单独引入核心模块就尅脱离Web环境
  • 重量级 (依赖于很多组件和依赖)

3、和Shiro 相比

1、shiro更轻量、更灵活

2、SpringSecurity功能比Shiro更强大,可以做单点登录

二、入门案例

1、创建springboot工程

在这里插入图片描述

springboot版本:2.3.7

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FRenyyOJ-1642823134584)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20211219113527777.png)]

2、引入相关依赖

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

3、编写一个简单的controller测试

//@RestController  = @RequestBody + @Controller  返回return内对应的值
@RestController 
@RequestMapping("test")
public class TestController {
    @GetMapping("hello")
    public String hello(){
        return "hello,security";
    }
}

4、启动springboot工程

1、在页面打开对应的controller

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qxmXRySP-1642823134585)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20211219143327728.png)]

进入界面如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nOzoMSEG-1642823134585)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20211219143341594.png)]

这就是springsecurity默认的登录页面,需要授权才能进入正的页面(注意导航栏的url地址最后**/login**)

2、输入用户名和密码进入页面,默认用户名:user 密码为springboot项目启动之后控制台内随机生成的密码 :747924b3-a85a-4e2f-b84a-374d41dc4b02 (都是springsecurity内自带的)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-htyayQIX-1642823134586)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20211219143537774.png)]

3、在页面内登录,进入如下页面:(注意导航栏地址最后的为自己写的controller层接口**/hello**

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rn4LH4sS-1642823134587)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20211219143646487.png)]

三、底层代码流程:三个重点过滤器

四、使用自己的数据库密码,进行登录配置

1、继承UsernamePasswordAuthenticationFilter方法

1、新建类继承UsernamePasswordAuthenticationFilter方法,重写其中的attemptAuthentication方法,如果认证成功,再重写其中的successfulAuthentication方法,否则重写unsuccessfulAuthentication方法。

2、使用自己数据库内部数据进行比对

两个重要接口:UserDetailsService、PasswordEncoder

1、新建类实现UserDetailsService接口,里面写查询数据库用户名和密码的过程。

2、编写查询数据的过程,返回User对象,这个User对象是安全框架提供的User对象

3、PasswordEncoder用于返回对User对象内的密码进行加密,BCryptPasswordEncoder方法对密码进行加密,是Spring Security官方推荐的密码解析器 基于Hash算法实现单向加密,可以通过strength控制密码强度,默认10.

五、Web权限方案

1、认证(登录过程)

1、设置登录的用户名和密码
1、通过配置文件配置

在properties文件中配置

server.port=8080
spring.security.user.name=a123
spring.security.user.password=123456

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OqmxRkTb-1642823134588)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220110153043107.png[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8aAeufGX-1642823135253)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220110153057363.png)]]

2、通过配置类

1、新建config包

2、创建SecurityConfig配置类,继承WebSecurityConfigurerAdapter类

package com.example.springsecurity.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Create on 2022/1/10 15:32
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //新建加密密码对象
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //对密码进行加密
        String encode = passwordEncoder.encode("123");
        //传入用户名,密码,角色
        auth.inMemoryAuthentication().withUser("lucy").password(encode).roles("admin");
    }
}

3、运行结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AYuu8D1c-1642823134588)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220110162052383.png)]

3、自定义编写实现类(使用数据库内)

1、创建配置类,设置使用哪个userDeailsService实现类

package com.example.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Create on 2022/1/10 16:33
 */
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

2、编写接口实现类

package com.example.springsecurity.Service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Create on 2022/1/10 16:38
 */
//userDetailsService和 配置类中 @Autowired下注入的名称相同
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User("mary",new BCryptPasswordEncoder().encode("123"),role);
    }
}

3、运行结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L7ZltMoE-1642823134589)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220110173709382.png)]

4、查询数据库完成用户认证(整合MybatisPlus完成数据库操作)
①引入对应的依赖
		<!--注意:为了防止idea更新pom文件maven资源自动更新卡死的问题,当idea版本为2020.x以上时,不在使用自动更新,右上角有maven小按钮,可以点击进行更新,快捷键为 MAC:Shift + Command + O
Windows:Ctrl + Shift + O-->
		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter </artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
②新建数据库(SpringSecurityTest)和对应的表(users)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4ZbNkYKy-1642823134589)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220121104957517.png)]

③新建实体类(JavaBean)
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Users {
    private Integer id;
    private String username;
    private String password;
}
④整合mp(mybaitsPlus)
package com.example.springsecurity.Mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springsecurity.entity.Users;

/**
 * @Create on 2022/1/21 11:08
 */
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
⑤在MyDetailsService调用Mapper里面的方法查询数据库进行用户认证
package com.example.springsecurity.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecurity.Mapper.UsersMapper;
import com.example.springsecurity.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Create on 2022/1/10 16:38
 */
//userDetailsService和 配置类中 @Autowired下注入的名称相同
@Service("userDetailsService")
@SuppressWarnings({"all"})
public class MyUserDetailsService implements UserDetailsService {
//    1、注入对应的mapper
    @Autowired
    private UsersMapper usersMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //此处传入的username为获取到表单中的username(账号)
        //2、mp中的条件构造器,用于执行对应的sql操作
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        //3、根据username查询数据库里的username字段
        //where username = ?
        queryWrapper.eq("username",username);
        //4、执行sql语句,得到一条记录,防止用户名重复
        Users users = usersMapper.selectOne(queryWrapper);
        //5、认证操作
        if(users==null){//数据库没有该用户,认证失败,抛出异常
            throw new UsernameNotFoundException("用户名不存在");
        }
        //用户名存在
        List<GrantedAuthority> role =
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),
                role);
    }
}
⑥添加mapper扫描

在启动类上加入注解@MapperScan

@SpringBootApplication
@MapperScan("com.example.springsecurity.Mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
⑦配置数据源信息

yaml、或者properties文件中配置

# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/springsecuritytest?serverTimezone=GMT%2B8
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
⑧具体运行时详细信息

1、先进入MyUserDetailService中,调用loadUserByUsername方法,判断对应的用户

2、自定义登录页面

1、在SecurityConfigTest类中新增配置方法

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        HashSet hashSet = new HashSet();
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //    1、新增配置方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
}

2、编写html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/user/login" method="post">
        用户名:<input type="text" name="username">
        <br/>
        密码:<input type="text" name="password">
        <input type="submit" value="登录">
    </form>
</body>
</html>

值得注意的是 ,html的代码name值必须是username和password,这是由于springsecurity内置觉得的,因为他的底层使用的就是从前端代码上获取到username和password的值。

3、访问测试

访问被保护的页面时,会出现自定义的登录页面,如下图,如果访问没被保护的,那么就会直接访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tgQClGV0-1642823134590)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220121202847681.png)]

2、授权(给定权限过程)

1、hasAuthority方法

当前主题具有指定的权限,有的话返回true,否则返回false

1、在SecurityConfigTest配置类中设置当前访问地址有哪些权限
 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                //新增配置权限
                    .antMatchers("/test/index").hasAuthority("admins")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
2、在UserDetailsService中,把返回user对象设置权限
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //此处传入的username为获取到表单中的username(账号)
        //2、mp中的条件构造器,用于执行对应的sql操作
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        //3、根据username查询数据库里的username字段
        //where username = ?
        queryWrapper.eq("username",username);
        //4、执行sql语句,得到一条记录,防止用户名重复
        Users users = usersMapper.selectOne(queryWrapper);
        //5、认证操作
        if(users==null){//数据库没有该用户,认证失败,抛出异常
            throw new UsernameNotFoundException("用户名不存在");
        }
        //用户名存在
        //赋予登录用户权限,该给的的权限可以与配置类中的相比较,以确定用户可以访问什么路径
        List<GrantedAuthority> role =
                AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),
                role);
    }
2、hasAnyAuthority当权限较多时

当权限较多时,在SecurityConfigTest配置类中

 //    1、新增配置方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                //1、hasAuthority方法
                    //.antMatchers("/test/index").hasAuthority("admins,manager")  //表示用户必须同时具有两个权限才可以访问该路径
                //2、hasAnyAuthority方法
                	.antMatchers("/test/index").hasAnyAuthority("admins,manager") //表示用户只要有其中一个权限即可访问该路径
                	.anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
3、hasRole方法

hasRole方法返回值为

 return "hasRole('ROLE_" + role + "')";

所以在配置类中配置该资源路径时,需要加上"ROLE_"+role

//    1、新增配置方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                //1、hasAuthority方法
                    //.antMatchers("/test/index").hasAuthority("admins,manager")  //表示用户必须同时具有两个权限才可以访问该路径
                //2、hasAnyAuthority方法
//                    .antMatchers("/test/index").hasAnyAuthority("admins,manager") //表示用户只要有其中一个权限即可访问该路径
                //3、hasRole方法  返回值为Role_+sole
                    .antMatchers("/test/index").hasRole("sale")
                    .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }

所以对应的在给登录的角色赋予权限时,要在权限之前加上

//表示用户有两个权限 
List<GrantedAuthority> role =
                AuthorityUtils.commaSeparatedStringToAuthorityList("admins,Role_sale");
4、hasAnyRole

同hasAnyAuthority,区别是在赋予角色值时加上前缀即可

5、自定义403无权限访问页面

在SecurityConfigTest配置类中进行配置

	@Override
    protected void configure(HttpSecurity http) throws Exception {
        //此处的为unauth.html为自己定义的页面
		http.exceptionHandling().accessDeniedPage("/unauth.html");
    }

3、认证和授权过程中注解的使用

(*表示不常用)

1、@Secured

*用户具有某个角色,可以访问

①在启动类上开启注解功能(配置类上也可以)

@EnableGlobalMethodSecurity(securedEnabled = true)

@SpringBootApplication
@MapperScan("com.example.springsecurity.Mapper")
//开启注解
@EnableGlobalMethodSecurity(securedEnabled = true)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
②配置controller层加上@Secured
	@GetMapping("update")
    @Secured({"Role_sale","Role_manager"}) //表示用于这两个权限中的其中一个或者同拥有才可以访问该路径,必须以"Role_"为前缀
    public String update(){
        return "hello update";
    }
③在userDetailsService中设置用户角色
 //设置权限
        List<GrantedAuthority> role =
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,Role_sale");
2、@PreAuthorize
①在启动类上开启注解功能

prePostEnabled = true

@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)

@SpringBootApplication
@MapperScan("com.example.springsecurity.Mapper")
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
②在controller方法上添加该注解
    @GetMapping("update")
//    @Secured({"Role_sale","Role_manager"})
    @PreAuthorize("hasAnyAuthority('admins')")//hasAnyAuthority、hasAuthority、hasRole、hasAnyRole都可以,表示在进入方法之前进行验证,方法内的操作不会被执行,如果有身份就进入,否则进入无权限页面
    public String update(){
        return "hello update";
    }
③在userDetailsService中设置用户角色

同上

*3、@PostAuthorize
①在启动类上开启注解功能

prePostEnabled = true

@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)

@SpringBootApplication
@MapperScan("com.example.springsecurity.Mapper")
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
②在controller方法上添加该注解
    @GetMapping("update")
//    @Secured({"Role_sale","Role_manager"})
//    @PreAuthorize("hasAnyAuthority('admins')")
    @PostAuthorize("hasAnyAuthority('admin')") //同@PreAuthorize注解,但是这个注解表示在方法执行之后才进行权限认证
    public String update(){
        System.out.println("update");
        return "hello update";
    }

执行之后,控制台会输出sout中的内容,但是当权限不足时,仍然跳转到无权限页面

③在userDetailsService中设置用户角色
*4、@PostFilter

方法返回数据进行过滤

①controller层
	@GetMapping("GetAll")
    @PostAuthorize("hasAnyAuthority('admins')")
    @PostFilter("filterObject.username=='admin2'")
    public List<Users> getAllUser(){
        ArrayList<Users> list = new ArrayList<>();
        list.add(new Users(1,"admin1","666"));
        list.add(new Users(2,"admin2","888"));
        System.out.println(list);
        return list;
    }

用户成功登录之后,只会返回 @PostFilter(“filterObject.username==‘admin2’”)需要的值,也就是list.add(new Users(2,“admin2”,“888”));

②网页返回结果如下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UaolExt0-1642823134591)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220122111756121.png)]

*5、@PreFilter

对方法传入值进行 过滤

①controller层
@GetMapping("getTest")
    @PostAuthorize("hasAnyAuthority('admins')")
    @PostFilter("filterObject.id%2==0")
    public List<Users> getTest(List<Users> list){
        for (Users users : list) {
            System.out.println(users.getId()+"\t"+ users.getUsername());
        }
        return list;
    }

对传入方法进行过滤

4、用户注销

①在配置类中添加退出映射地址
 	 //    1、新增配置方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //退出登录配置
        //第一个参数为退出的
        //第二个参数为退出成功之后跳转的接口
        http.logout().logoutUrl("/logout").
                logoutSuccessUrl("/test/hello").permitAll();
        //配置没有权限访问的页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/success.html").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                //1、hasAuthority方法
                    //.antMatchers("/test/index").hasAuthority("admins,manager")  //表示用户必须同时具有两个权限才可以访问该路径
                //2、hasAnyAuthority方法
//                    .antMatchers("/test/index").hasAnyAuthority("admins,manager") //表示用户只要有其中一个权限即可访问该路径
                //3、hasRole方法  返回值为Role_+sole
                    .antMatchers("/test/index").hasRole("sale")
                    .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }

②对应的前端退出登录时内部的超链接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
登录成功
<!--此处的/login为springsecurity内置的-->
<a href="/logout">退出</a>
</body>
</html>

六、自动登录

使用springsecurity的安全框架实现自动登录(记住我)

1、在配置类中注入数据源

新建配置类也行,继续在SecurityConfigTest中写也行,以下在SecurityConfigTest中写

//注入数据源
    @Autowired
    private DataSource dataSource;
2、导入Bean类
	@Bean
    public PersistentTokenRepository repository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //自动创建表 无需手动创建 springsecurity内置的创建表,此处无需手动创建,值得注意的是,当第一次运行之后,需要把这段代码注释掉,因为第一次运行之后该表已经存在
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
jdbcTokenRepository.setCreateTableOnStartup(true);

自动创建的表如下(已经试验过,所以有数据,其中的数据就是自动登录时保存的用户信息,此表可以看出,username的值必须唯一,可以不唯一,最后会讲到为什么)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x9sr2wIZ-1642910554981)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123112748221.png)]

3、更新configure(HttpSecurity http)方法,加入remember-me操作
 @Override
    protected void configure(HttpSecurity http) throws Exception {
        //退出登录配置
        //第一个参数为退出的
        //第二个参数为退出成功之后跳转的接口
        http.logout().logoutUrl("/logout").
                logoutSuccessUrl("/test/hello").permitAll();
        //配置没有权限访问的页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin() //自定义编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/success.html").permitAll()  //登录成功之后跳转到的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() //表示访问这些路径时不需要认证
                //1、hasAuthority方法
                    //.antMatchers("/test/index").hasAuthority("admins,manager")  //表示用户必须同时具有两个权限才可以访问该路径
                //2、hasAnyAuthority方法
//                    .antMatchers("/test/index").hasAnyAuthority("admins,manager") //表示用户只要有其中一个权限即可访问该路径
                //3、hasRole方法  返回值为Role_+sole
                    .antMatchers("/test/index").hasRole("sale")
                    .anyRequest().authenticated()
                //自动登录
                    .and().rememberMe().tokenRepository(repository())
                //时间600s
                    .tokenValiditySeconds(600)
                    .userDetailsService(userDetailsService)
                .and().csrf().disable(); //关闭csrf防护
    }
4、在html页面上添加自动登录复选框
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/user/login" method="post">
        用户名:<input type="text" name="username">
        <br/>
        密码:<input type="text" name="password">
        <br/>
        <!--此处的name值必须是remember-me-->
        <input type="checkbox" name="remember-me"> 自动登录
        <input type="submit" value="登录">
    </form>
</body>
</html>
5、测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-laExi2b0-1642910554982)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123112422826.png)]

登录后查看

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ywsccjpN-1642910554983)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123112506994.png)]

点击选择cookie
在这里插入图片描述
可以看到我们加入的cookie

登录之后可以查看到对应的表内容如下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VJqWbQMj-1642910554983)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123112941523.png)]

最后值得注意的是,当我们使用两个不同的浏览器去登录同一个账号时,此时username相同,登录成功之后,该表内部为有两个相同的username字段,如下图所示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BAgk5F1x-1642910554985)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123113422392.png)]

当在其中一个浏览器上点击退出登录时,会同时删除其中username相同的数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YJMGWQS3-1642910554986)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20220123113522821.png)]

七、CSRF(跨站请求伪造)

1、注释掉配置类中关闭的CSRF功能

csrf提供保护POST、PUT、DELETE请求

关闭之后表示开启

//                .and().csrf().disable(); //关闭csrf防护
2、在登录的html页面中加入
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<input th:name="${_csrf.parameterName}" th:value="${_csrf.token}" type="hidden">

*必须注释掉第一步才可以写第二步,否则报错

结尾:以上内容为本人学习笔记,学习资源来自尚硅谷课程SpringSecurity
仅仅做为个人总结,各自努力,最高处见。

  • 22
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security 参考 1 第一部分前言 15 1.入门 16 2.介绍 17 2.1什么是Spring Security? 17 2.2历史 19 2.3版本编号 20 2.4获得Spring安全 21 2.4.1使用Maven 21 Maven仓库 21 Spring框架 22 2.4.2 Gradle 23 Gradle存储库 23 使用Spring 4.0.x和Gradle 24 2.4.3项目模块 25 核心 - spring-security-core.jar 25 远程处理 - spring-security-remoting.jar 25 Web - spring-security-web.jar 25 配置 - spring-security-config.jar 26 LDAP - spring-security-ldap.jar 26 ACL - spring-security-acl.jar 26 CAS - spring-security-cas.jar 26 OpenID - spring-security-openid.jar 26 测试 - spring-security-test.jar 26 2.4.4检出来源 26 3. Spring Security 4.2的新特性 27 3.1 Web改进 27 3.2配置改进 28 3.3杂项 28 4.样品和指南(从这里开始) 28 5. Java配置 29 5.1 Hello Web安全Java配置 29 5.1.1 AbstractSecurityWebApplicationInitializer 31 5.1.2 AbstractSecurityWebApplicationInitializer不存在Spring 31 5.1.3使用Spring MVC的AbstractSecurityWebApplicationInitializer 32 5.2 HttpSecurity 32 5.3 Java配置和表单登录 34 5.4授权请求 35 5.5处理注销 36 5.5.1 LogoutHandler 37 5.5.2 LogoutSuccessHandler 37 5.5.3更多注销相关参考 38 5.6认证 38 5.6.1内存认证 38 5.6.2 JDBC认证 39 5.6.3 LDAP认证 39 5.6.4 AuthenticationProvider 41 5.6.5 UserDetailsService 41 5.6.6 LDAP认证 41 5.7多个HttpSecurity 41 5.8方法安全性 43 5.8.1 EnableGlobalMethodSecurity 43 5.8.2 GlobalMethodSecurityConfiguration 44 5.9后处理配置的对象 45 5.10自定义DSL 46 6.安全命名空间配置 47 6.1简介 47 6.1.1命名空间的设计 49 6.2安全命名空间配置入门 50 6.2.1 web.xml配置 50 6.2.2最小的配置 50 6.2.3表单和基本登录选项 52 设置默认的登录目的地 54 6.2.4注销处理 54 6.2.5使用其他身份验证提供程序 55 添加密码编码器 56 6.3高级Web功能 56 6.3.1记得我认证 56 6.3.2添加HTTP / HTTPS通道安全 57 6.3.3会话管理 57 检测超时 57 并发会话控制 58 会话固定攻击保护 59 6.3.4 OpenID支持 60 属性交换 61 6.3.5响应头 62 6.3.6添加你自己的过滤器 62 设置一个自定义的AuthenticationEntryPoint 64 6.4方法安全 64 6.4.1 元素 65 使用protect-pointcut添加安全性切入点 66 6.5默认AccessDecisionManager 67 6.5.1自定义AccessDecisionManager 67 6.6验证管理器和命名空间 67 7.示例应用程序 69 7.1教程示例 69 7.2联系人 69 7.3 LDAP样本 71 7.4 OpenID示例 71 7.5 CAS样品 71 7.6 JAAS样品 72 7.7预认证样本 72 8. Spring Security社区 72 8.1问题跟踪 72 8.2成为参与 73 8.3更多信息 73 第二部分 架构与实现 73 9.技术概述 73 9.1运行环境 73 9.2核心组件 74 9.2.1 SecurityContextHolder,SecurityContext和认证对象 74 获取有关当前用户的信息 75 9.2.2 UserDetailsService 75 9.2.3授予权力 77 9.2.4总结 77 9.3认证 78 9.3.1什么是Spring Security中的认证? 78 9.3.2直接设置SecurityContextHolder内容 80 9.4 Web应用程序中的身份验证 81 9.4.1 ExceptionTranslationFilter 82 9.4.2 AuthenticationEntryPoint 82 9.4.3认证机制 82 9.4.4在请求之间存储SecurityContext 83 9.5 Spring Security中的访问控制(授权) 84 9.5.1安全和AOP建议 84 9.5.2安全对象和AbstractSecurityInterceptor 85 什么是配置属性? 85 RunAsManager 86 AfterInvocationManager 86 扩展安全对象模型 87 9.6本地化 87 10.核心服务 89 10.1 AuthenticationManager,ProviderManager和AuthenticationProvider 89 10.1.1成功认证时清除证书 91 10.1.2 DaoAuthenticationProvider 91 10.2 UserDetailsService实现 92 10.2.1内存认证 92 10.2.2 JdbcDaoImpl 93 权威组织 94 10.3密码编码 94 10.3.1什么是散列? 95 10.3.2添加盐到哈希 95 10.3.3散列和认证 96 10.4Jackson 支持 96 第三部分 测试 97 11.测试方法安全性 97 11.1安全测试设置 98 11.2 @WithMockUser 98 11.3 @WithAnonymousUser 100 11.4 @用户详细信息 101 11.5 @WithSecurityContext 102 11.6测试元注释 104 12. Spring MVC测试集成 104 12.1设置MockMvc和Spring Security 104 12.2 SecurityMockMvcRequestPostProcessors 105 12.2.1使用CSRF保护进行测试 105 12.2.2在Spring MVC测试中以用户身份运行测试 106 12.2.3使用RequestPostProcessor在Spring MVC测试中以用户身份运行 106 作为用户在Spring MVC测试中使用注释运行 108 12.2.4测试HTTP基本认证 109 12.3 SecurityMockMvcRequestBuilders 109 12.3.1测试基于表单的认证 109 12.3.2测试注销 110 12.4 SecurityMockMvcResultMatchers 110 12.4.1未经认证的声明 111 12.4.2认证断言 111 第四部分 Web应用程序安全 112 13.安全过滤器链 112 13.1 DelegatingFilterProxy 112 13.2 FilterChainProxy 113 13.2.1绕过滤网链 115 13.3过滤器排序 115 13.4请求匹配和HttpFirewall 116 13.5与其他基于过滤器的框架一起使用 118 13.6高级命名空间配置 118 14.核心安全筛选器 119 14.1 FilterSecurityInterceptor 119 14.2 ExceptionTranslationFilter 121 14.2.1 AuthenticationEntryPoint 122 14.2.2 AccessDeniedHandler 122 14.2.3 SavedRequest和RequestCache接口 123 14.3 SecurityContextPersistenceFilter 123 14.3.1 SecurityContextRepository 124 14.4 UsernamePasswordAuthenticationFilter 125 14.4.1认证成功与失败的应用流程 125 15. Servlet API集成 127 15.1 Servlet 2.5+集成 127 15.1.1 HttpServletRequest.getRemoteUser() 127 15.1.2 HttpServletRequest.getUserPrincipal() 127 15.1.3 HttpServletRequest.isUserInRole(String) 128 15.2 Servlet 3+集成 128 15.2.1 HttpServletRequest.authenticate(HttpServletResponse) 128 15.2.2 HttpServletRequest.login(String,String) 129 15.2.3 HttpServletRequest.logout() 129 15.2.4 AsyncContext.start(Runnable) 129 15.2.5异步Servlet支持 130 15.3 Servlet 3.1+集成 131 15.3.1 HttpServletRequest#changeSessionId() 132 16.基本和摘要式身份验证 132 16.1 BasicAuthenticationFilter 132 16.1.1配置 132 16.2 DigestAuthenticationFilter 133 16.2.1配置 135 17.记住我的身份验证 136 17.1概述 136 17.2简单的基于哈希的令牌方法 136 17.3持久性令牌方法 137 17.4记住我的接口和实现 138 17.4.1 TokenBasedRememberMeServices 138 17.4.2 PersistentTokenBasedRememberMeServices 139 18.跨站点请求伪造(CSRF) 140 18.1 CSRF攻击 140 18.2同步器令牌模式 141 18.3何时使用CSRF保护 142 18.3.1 CSRF保护和JSON 142 18.3.2 CSRF和无状态浏览器应用程序 143 18.4使用Spring Security CSRF保护 143 18.4.1使用适当的HTTP动词 144 18.4.2配置CSRF保护 144 18.4.3包含CSRF令牌 145 表单提交 145 Ajax和JSON请求 145 CookieCsrfTokenRepository 146 18.5 CSRF警告 147 18.5.1超时 148 18.5.2登录 148 18.5.3注销 149 18.5.4多部分(文件上传) 149 在Spring Security之前放置MultipartFilter 150 包含CSRF令牌 151 18.5.5隐藏的HttpMethodFilter 151 18.6覆盖默认值 151 19. CORS 152 20.安全性HTTP响应头 154 20.1默认的安全头 154 20.1.1缓存控制 157 20.1.2内容类型选项 158 20.1.3 HTTP严格传输安全(HSTS) 159 20.1.4 HTTP公钥密码(HPKP) 161 20.1.5 X-Frame-Options 163 20.1.6 X-XSS保护 164 20.1.7内容安全策略(CSP) 165 配置内容安全策略 166 其他资源 168 20.1.8推荐人政策 168 配置引用者策略 169 20.2自定义标题 169 20.2.1静态头 169 20.2.2标题作者 170 20.2.3 DelegatingRequestMatcherHeaderWriter 171 21.会议管理 172 21.1 SessionManagementFilter 173 21.2 SessionAuthenticationStrategy 173 21.3并发控制 174 21.3.1查询当前通过身份验证的用户及其会话的SessionRegistry 176 22.匿名身份验证 177 22.1概述 177 22.2配置 178 22.3 AuthenticationTrustResolver 179 23. WebSocket安全 180 23.1 WebSocket配置 181 23.2 WebSocket身份验证 182 23.3 WebSocket授权 182 23.3.1 WebSocket授权说明 183 消息类型的WebSocket授权 184 目的地上的WebSocket授权 184 23.3.2出站消息 185 23.4执行相同的来源政策 185 23.4.1为什么同源? 185 23.4.2 Spring WebSocket允许的来源 186 23.4.3添加CSRF到Stomp头 186 23.4.4在WebSockets中禁用CSRF 187 23.5使用SockJS 187 23.5.1 SockJS和框架选项 187 23.5.2轻松放松CSRF 188 第五部分授权 190 24.授权体系结构 190 24.1当局 190 24.2预调用处理 191 24.2.1 AccessDecisionManager 191 24.2.2基于投票的AccessDecisionManager实现 192 RoleVoter 193 AuthenticatedVoter 194 自定义选民 194 24.3调用处理后 194 24.4分层角色 196 25.安全的对象实现 197 25.1 AOP联盟(MethodInvocation)安全拦截器 197 25.1.1显式MethodSecurityInterceptor配置 197 25.2 AspectJ(JoinPoint)安全拦截器 198 26.基于表达式的访问控制 200 26.1概述 200 26.1.1通用内置表达式 201 26.2网络安全表达式 202 26.2.1在Web安全表达式中引用Bean 203 26.2.2 Web安全表达式中的路径变量 204 26.3方法安全表达式 204 26.3.1 @Pre和@Post注释 205 访问控制使用@PreAuthorize和@PostAuthorize 205 使用@PreFilter和@PostFilter进行过滤 207 26.3.2内置表达式 207 PermissionEvaluator接口 208 方法安全元注释 209 第六部分 其他主题 209 27.域对象安全(ACL) 209 27.1概述 209 27.2重要概念 211 27.3入门 214 28.预认证方案 216 28.1预认证框架类 216 28.1.1 AbstractPreAuthenticatedProcessingFilter 217 J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource 217 28.1.2 PreAuthenticatedAuthenticationProvider 218 28.1.3 Http403ForbiddenEntryPoint 218 28.2具体实施 219 28.2.1请求头认证(Siteminder) 219 Siteminder示例配置 219 28.2.2 Java EE容器认证 220 29. LDAP认证 220 29.1概述 220 29.2在Spring Security中使用LDAP 221 29.3配置LDAP服务器 221 29.3.1使用嵌入式测试服务器 222 29.3.2使用绑定认证 222 29.3.3加载权限 223 29.4实现类 223 29.4.1 LdapAuthenticator实现 224 通用功能 224 认证者 225 PasswordComparisonAuthenticator 225 29.4.2连接到LDAP服务器 225 29.4.3 LDAP搜索对象 225 FilterBasedLdapUserSearch中 225 29.4.4 LdapAuthoritiesPopulator 226 29.4.5 Spring Bean配置 226 29.4.6 LDAP属性和定制的UserDetails 227 29.5 Active Directory认证 228 29.5.1 ActiveDirectoryLdapAuthenticationProvider 228 活动目录错误代码 229 30. JSP标签库 230 30.1声明Taglib 230 30.2授权标签 230 30.2.1禁用测试的标签授权 231 30.3认证标签 232 30.4 accesscontrollist标签 232 30.5 csrfInput标签 233 30.6 csrfMetaTags标签 233 31 Java认证和授权服务(JAAS)提供者 235 31.1概述 235 31.2摘要:Java认证提供者 235 31.2.1 JAAS CallbackHandler 235 31.2.2 JAAS权威机构 236 31.3 DefaultJaasAuthenticationProvider 237 31.3.1 InMemoryConfiguration 237 31.3.2 DefaultJaasAuthenticationProvider示例配置 238 31.4 JaasAuthenticationProvider 239 31.5作为主题运行 240 32. CAS认证 240 32.1概述 240 32.2 CAS的工作原理 240 32.2.1 Spring安全和CAS交互序列 241 32.3 CAS客户端的配置 244 32.3.1服务票据认证 244 32.3.2单一注销 246 32.3.3使用CAS认证无状态服务 249 配置CAS以获取代理授予票证 249 使用代理票证调用无状态服务 250 32.3.4代理票证认证 251 33. X.509认证 253 33.1概述 253 33.2将X.509身份验证添加到您的Web应用程序 253 33.3在Tomcat中设置SSL 254 34.运行认证替换 255 34.1概述 255 34.2配置 255 35. Spring Security加密模块 257 35.1简介 257 35.2加密器 257 35.2.1 BytesEncryptor 257 35.2.2 TextEncryptor 258 35.3关键发电机 258 35.3.1 BytesKeyGenerator 258 35.3.2 StringKeyGenerator 259 35.4密码编码 259 36.并发支持 260 36.1 DelegatingSecurityContextRunnable 260 36.2 DelegatingSecurityContextExecutor 262 36.3 Spring安全性并发类 264 37. Spring MVC集成 265 37.1 @EnableWebMvcSecurity 265 37.2 MvcRequestMatcher 265 37.3 @AuthenticationPrincipal 268 37.4 Spring MVC异步集成 271 37.5 Spring MVC和CSRF集成 271 37.5.1自动令牌包含 271 37.5.2解析CsrfToken 272 第七部分 Spring数据集成 273 38. Spring Data&Spring安全配置 273 39. @Query中的安全表达式 273 第八部分 附录 274 40.安全数据库模式 274 40.1用户模式 274 40.1.1集团当局 274 40.2持久登录(记得我)架构 275 40.3 ACL模式 275 40.3.1 HyperSQL 276 40.3.2 PostgreSQL 277 40.3.3 MySQL和MariaDB 278 40.3.4 Microsoft SQL Server 279 40.3.5 Oracle数据库 280 41.安全命名空间 282 41.1 Web应用程序安全性 282 41.1.1 282 41.1.2 282 属性 283 的子元素 285 41.1.3 286 的父元素 286 属性 286 41.1.4 286 属性 287 父元素 287 41.1.5 <headers> 287 <headers>属性 288 <headers>的父元素 288 <headers>的子元素 288 41.1.6 289 属性 289 的父元素 289 41.1.7 289 属性 289 的父元素 290 41.1.8 290 属性 290 的父元素 290 41.1.9 290 的子元素 290 41.1.10 291 属性 291 的父元素 291 41.1.11 291 属性 291 的父元素 291 41.1.12 291 属性 292 的父元素 292 41.1.13 <frame-options> 292 <frame-options>属性 292 <frame-options>的父元素 293 41.1.14 [removed] 293 [removed]属性 293 [removed]的父元素 294 41.1.15 294 属性 294 的父元素 294 41.1.16 <header> 294 <header-attributes>属性 294 <header>的父元素 295 41.1.17 295 的父元素 295 属性 295 41.1.18 295 父元素 296 属性 296 41.1.19 296 的父元素 296 属性 296 41.1.20 <expression-handler> 297 <expression-handler>的父元素 297 属性 297 41.1.21 <form-login> 297 <form-login>的父元素 298 <form-login>属性 298 41.1.22 299 的父元素 300 属性 300 41.1.23 元素 300 属性 300 41.1.24 300 的父元素 300 属性 301 41.1.25 302 的父元素 302 属性 302 41.1.26 302 父元素 302 属性 303 41.1.27 303 的父元素 303 属性 303 的子元素 305 41.1.28 305 的父元素 305 属性 305 的子元素 305 41.1.29 306 的父元素 306 属性 306 41.1.30 306 的父元素 306 的子元素 307 41.1.31 307 的父元素 307 属性 307 41.1.32 307 的父元素 307 属性 307 41.1.33 元素 309 的父元素 309 属性 309 41.1.34 309 的父元素 309 属性 309 的子元素 310 41.1.35 311 的父元素 311 属性 311 41.1.36 312 的父元素 312 属性 312 41.1.37 313 属性 313 的子元素 313 41.1.38 313 的父元素 313 属性 313 41.1.39 314 属性 314 的子元素 314 41.2 WebSocket安全 314 41.2.1 315 属性 315 的子元素 316 41.2.2 316 的父元素 316 属性 316 41.3认证服务 317 41.3.1 317 属性 317 的子元素 317 41.3.2 318 的父元素 318 属性 318 的子元素 318 41.3.3 319 属性 319 41.3.4 320 的父元素 320 属性 320 的子元素 320 41.3.5 320 的父元素 321 属性 321 41.3.6 321 属性 321 的子元素 321 41.3.7 321 的父元素 322 属性 322 41.4方法安全 322 41.4.1 322 属性 322 的子元素 324 41.4.2 324 的父元素 324 属性 324 41.4.3 324 的父元素 325 325 41.4.4 325 的父元素 325 属性 325 41.4.5 325 的父元素 325 属性 325 41.4.6 326 的父元素 326 属性 326 41.4.7使用安全方法 326 父节点 326 属性 326 41.4.8 326 属性 327 的子元素 327 41.4.9 327 属性 327 的子元素 327 41.4.10 327 父元素 328 属性 328 41.5 LDAP名称空间选项 328 41.5.1使用。定义LDAP服务器 328 属性 329 41.5.2 329 的父元素 329 属性 329 的子元素 331 41.5.3 331 的父元素 331 属性 332 的子元素 332 41.5.4 332 属性 332 42.春季安全依赖 333 42.1 spring-security-core 334 42.2 spring-security-remoting 334 42.3 spring-security-web 335 42.4 spring-security-ldap 335 42.5 spring-security-config 336 42.6 spring-security-acl 336 42.7 spring-security-cas 337 42.8 spring-security-openid 337 42.9 spring-security-taglibs 338 43.代理服务器配置 338 44. Spring Security FAQ 339 44.1一般问题 339 44.1.1 Spring Security是否会处理我所有的应用程序安全要求? 339 44.1.2为什么不使用web.xml安全? 339 44.1.3需要哪些JavaSpring Framework版本? 341 44.1.4我是Spring Security的新手,我需要构建一个支持通过HTTPS进行CAS单点登录的应用程序,同时允许对某些URL进行本地基本身份验证,并对多个后端用户信息源(LDAP和JDBC)进行身份验证。我已经复制了一些我发现的配置文件,但不起作用。什么可能是错的? 341 44.2常见问题 342 44.2.1当我尝试登录时,我收到一条错误消息,指出“Bad Credentials”。怎么了? 343 44.2.2当我尝试登录时,我的应用程序进入“无限循环”,发生了什么事? 344 44.2.3我收到一条异常消息“访问被拒绝(用户是匿名的)”。怎么了? 344 44.2.4即使在我退出应用程序之后,为什么还能看到安全的页面? 345 44.2.5我得到一个异常,消息“在SecurityContext中没有找到认证对象”。怎么了? 345 44.2.6我无法使LDAP认证正常工作。我的配置有什么问题? 345 44.2.7会话管理 346 44.2.8我使用Spring Security的并发会话控制来防止用户一次登录多次。登录后打开另一个浏览器窗口时,不会阻止我再次登录。为什么我可以多次登录? 347 44.2.9为什么在通过Spring Security进行身份验证时会话ID发生了变化? 347 44.2.10我正在使用Tomcat(或其他一些servlet容器),并为我的登录页面启用了HTTPS,之后切换回HTTP。这是行不通的 - 我只是在认证之后回到登录页面。 347 44.2.11我没有在HTTP和HTTPS之间切换,但是我的会话仍然丢失 348 44.2.12我试图使用并发会话控制支持,但是不会让我重新登录,即使我确定我已经注销并且没有超出允许的会话。 348 44.2.13 Spring Security正在创建一个会话,即使我已经配置了它,通过设置create-session属性为永远不会。 348 44.2.14执行POST时,我得到了一个403 Forbidden 349 44.2.15我正在使用RequestDispatcher将请求转发到另一个URL,但是我的安全限制没有被应用。 349 44.2.16我已经将Spring Security的元素添加到我的应用程序上下文中,但是如果将安全注释添加到我的Spring MVC控制器bean(Struts操作等)中,那么它们似乎没有效果。 349 44.2.17我有一个肯定被认证的用户,但是当我在一些请求期间尝试访问SecurityContextHolder时,认证是空的。为什么我看不到用户信息? 350 44.2.18在使用URL属性时,授权JSP标记不尊重我的方法安全注释。 350 44.3 Spring安全体系结构问题 350 44.3.1我如何知道X是哪个包? 350 44.3.2名称空间元素如何映射到传统的bean配置? 351 44.3.3“ROLE_”是什么意思,为什么我的角色名字需要它? 351 44.3.4如何知道添加到我的应用程序中的哪些依赖关系与Spring Security一起使用? 352 44.3.5运行嵌入式ApacheDS LDAP服务器需要哪些依赖关系? 352 44.3.6什么是UserDetailsService,我需要一个吗? 353 44.4共同的“Howto”请求 353 44.4.1我需要登录更多的信息,而不仅仅是用户名。如何添加对额外登录字段(例如公司名称)的支持? 354 44.4.2如果只有所请求的URL的片段值不同(例如/ foo#bar和/ foo#blah),我该如何应用不同的拦截url链接? 354 44.4.3如何在UserDetailsService中访问用户的IP地址(或其他Web请求数据)? 354 44.4.4如何从UserDetailsService访问HttpSession? 355 44.4.5如何在UserDetailsService中访问用户的密码? 355 44.4.6如何动态定义应用程序中的安全URL? 355 44.4.7如何针对LDAP进行身份验证,但从数据库加载用户角色? 357 44.4.8我想修改由命名空间创建的bean的属性,但是模式中没有任何东西支持它。我可以做什么放弃命名空间的使用? 358 45.从3.x迁移到4.x 359

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值